Python 在元组中存储classmethod引用不像在变量中那样有效
输出:Python 在元组中存储classmethod引用不像在变量中那样有效,python,Python,输出: #!/usr/bin/python class Bar(object): @staticmethod def ruleOn(rule): if isinstance(rule, tuple): print rule[0] print rule[0].__get__(None, Foo) else: print rule class Foo(object): @classmethod def callRule(cl
#!/usr/bin/python
class Bar(object):
@staticmethod
def ruleOn(rule):
if isinstance(rule, tuple):
print rule[0]
print rule[0].__get__(None, Foo)
else:
print rule
class Foo(object):
@classmethod
def callRule(cls):
Bar.ruleOn(cls.RULE1)
Bar.ruleOn(cls.RULE2)
@classmethod
def check(cls):
print "I am check"
RULE1 = check
RULE2 = (check,)
Foo.callRule()
正如您所看到的,我试图在元组中存储对classmethod函数的引用,以备将来使用
但是,它似乎存储对象本身,而不是对绑定函数的引用
正如您所见,它适用于变量引用
获取它的唯一方法是使用\uuuu get\uuu
,它需要它所属的类的名称,而在规则
变量赋值时,该名称不可用
有什么想法吗?这是因为方法实际上是Python中的函数。只有在构造的类实例上查找它们时,它们才会成为绑定方法。有关更多详细信息,请参阅我对的回答。非元组变量之所以有效,是因为它在概念上与访问classmethod相同 如果要将绑定的classmethods分配给类属性,则必须在构造类后执行此操作:
<bound method type.check of <class '__main__.Foo'>>
<classmethod object at 0xb7d313a4>
<bound method type.check of <class '__main__.Foo'>>
谢谢,这很有道理。只是出于好奇,在构建类名的过程中,有没有办法检索类名?没有。在执行类主体时,类对象不存在。最好是使用类装饰器或元类绑定函数。
class Foo(object):
@classmethod
def callRule(cls):
Bar.ruleOn(cls.RULE1)
Bar.ruleOn(cls.RULE2)
@classmethod
def check(cls):
print "I am check"
Foo.RULE1 = Foo.check
Foo.RULE2 = (Foo.check,)