2

考虑以下情况:

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()"

我可以调用获取绑定方法unshadowedFoo它工作正常:

>>> 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'>>吗?

4

1 回答 1

0

在这个关于如何绑定未绑定方法的答案中似乎找到了一个潜在的答案(可能不是最好的) 。所以我们可以这样做:

>>> 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
于 2013-09-24T03:51:41.643 回答