考虑以下情况:
class Meta(type):
def shadowed(cls):
print "Meta.shadowed()"
def unshadowed(cls):
print "Meta.unshadowed()"
class Foo(object):
__metaclass__ = Meta
def shadowed(self):
print "Foo.shadowed()"
我可以调用unshadowed
上的绑定方法Foo
,它运行正常:
>>> Foo.unshadowed
<bound method Meta.unshadowed of <class '__main__.Foo'>>
>>> Foo.unshadowed()
Meta.unshadowed()
但是,我似乎无法在shadowed
上获取绑定方法Foo
- 它指向我,而不是必须使用Foo
实例调用的未绑定方法:
>>> Foo.shadowed
<unbound method Foo.shadowed>
>>> Foo.shadowed()
Traceback (most recent call last):
File "<pyshell#45>", line 1, in <module>
Foo.shadowed()
TypeError: unbound method shadowed() must be called with Foo instance as first argument (got nothing instead)
有没有办法获得<bound method Meta.shadowed of <class '__main__.Foo'>>
?
答案 0 :(得分:0)
似乎在this answer中找到了关于如何绑定未绑定方法的一个潜在答案(可能不是最好的答案)。所以我们可以这样做:
>>> Meta.shadowed.__get__(Foo, Meta)()
Meta.shadowed()
更好的示范:
class Meta(type):
def shadowed(cls):
print "Meta.shadowed() on %s" % (cls.__name__,)
def unshadowed(cls):
print "Meta.unshadowed() on %s" % (cls.__name__,)
class Foo(object):
__metaclass__ = Meta
def shadowed(self):
print "Foo.shadowed()"
class Bar(object):
__metaclass__ = Meta
Bar.unshadowed() #Meta.unshadowed() on Bar
Bar.shadowed() #Meta.shadowed() on Bar
Foo.unshadowed() #Meta.unshadowed() on Foo
#Foo.shadowed() #TypeError
Meta.shadowed.__get__(Foo, Meta)() #Meta.shadowed() on Foo