为什么
python实例方法可以调用,但静态方法和类方法不可调用?
我做了以下事情:
class Test():
class_var = 42
@classmethod
def class_method(cls):
pass
@staticmethod
def static_method():
pass
def instance_method(self):
pass
for attr, val in vars(Test).items():
if not attr.startswith("__"):
print (attr, "is %s callable" % ("" if callable(val) else "NOT"))
结果是:
static_method is NOT callable
instance_method is callable
class_method is NOT callable
class_var is NOT callable
从技术上讲,这可能是因为实例方法对象可能具有以特定方式设置的特定属性(不是)(可能是__call__).为什么会出现这种不对称,或者它的用途是什么?
我在学习python检查工具时遇到了这个问题.
评论的其他评论:
注释中链接的SO答案表示静态/类方法是descriptors,它们是不可调用的.现在我很好奇,为什么描述符不可调用,因为描述符是具有特定属性(__get __,__ set __,__ del __之一)定义的类.