python - 调用实例或类方法,以适当者为准
问题描述
这个问题提到了一种区分实例方法(传递self
)和静态方法(什么都不传递)的技巧:
class X:
def id(self=None):
if self is None:
# It's being called as a static method
else:
# It's being called as an instance method
(汤姆斯威利的学分)
但是,当继承发挥作用时,这很快就会遇到问题,因为静态方法没有self
或cls
因此无法在消息接收器上调用适当的方法。
我的问题是,我可以这样做吗?
class X:
def get(self_or_cls):
if self_or_cls turns out to be cls:
return self_or_cls.class_method()
else:
return self_or_cls.instance_method()
class Y(X):
foo = str
@classmethod
def class_method(cls):
return cls.foo
def instance_method(self):
return self.foo()
>>> Y.get()
<class 'str'>
>>> Y().get()
''
任何黑客表示赞赏!
解决方案
在此答案的帮助下,我为您找到了一种可能的技巧:
class Custommethod:
def __get__(self, ins, cls):
if ins is None:
return lambda : cls.class_method()
else:
return lambda : ins.instance_method()
class X:
get = Custommethod()
class Y(X):
foo = str
@classmethod
def class_method(cls):
return cls.foo
def instance_method(self):
return self.foo()
print(Y.get()) # <class 'str'>
print(Y().get()) # ''
推荐阅读
- powershell - Exit and Continue 脚本(例如获取PATH环境改变效果)
- php - Buddypress groups_create_group 未定义
- tfs - 将集合从 TFS 2015 迁移到 TFS 2018
- c# - 通过 sender 参数访问后台工作程序
- python - 比较 2 个 CSV 文件并将一个文件中的值添加到另一个匹配项
- oxyplot - Xamarin Forms WPF项目中的OxyPlot,如何更改跟踪器文本颜色
- javascript - 重写reduce方法js的问题
- angular - Nativescript + Angular ScrollView 滚动到最终监听器
- java - 如何在JAVA中动态转义JSON中的双引号
- java - Spring Data Rest:发布与非导出实体相关的实体