#!/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()
输出:
<bound method type.check of <class '__main__.Foo'>>
<classmethod object at 0xb7d313a4>
<bound method type.check of <class '__main__.Foo'>>
如您所见,我正试图在元组中存储对classmethod函数的引用,以供将来使用。你知道吗
但是,它似乎存储对象本身,而不是引用绑定函数。你知道吗
如您所见,它适用于变量引用。你知道吗
获取它的唯一方法是使用__get__
,它需要它所属的类的名称,而在RULE
变量赋值时该名称不可用。你知道吗
有什么想法吗?你知道吗
这是因为方法实际上是Python中的函数。只有在构造的类实例上查找它们时,它们才会成为绑定方法。有关详细信息,请参阅我对this question的回答。非元组变量之所以有效,是因为它在概念上与访问classmethod相同。你知道吗
如果要将绑定的classmethods分配给类属性,则必须在构造类之后执行此操作:
相关问题 更多 >
编程相关推荐