200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > python实例方法不可以用类调用_为什么python静态/类方法不可调用?

python实例方法不可以用类调用_为什么python静态/类方法不可调用?

时间:2023-02-01 20:41:32

相关推荐

python实例方法不可以用类调用_为什么python静态/类方法不可调用?

为什么

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 __之一)定义的类.

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。