Python 当类具有相同名称的方法时,如何获取从元类派生的绑定方法
考虑以下情况:Python 当类具有相同名称的方法时,如何获取从元类派生的绑定方法,python,methods,instance,metaclass,Python,Methods,Instance,Metaclass,考虑以下情况: 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()" 我可以在Foo上
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()"
我可以在Foo
上调用get-bound方法unshadowed
,它可以正常工作:
>>> Foo.unshadowed
<bound method Meta.unshadowed of <class '__main__.Foo'>>
>>> Foo.unshadowed()
Meta.unshadowed()
有没有办法获得
?关于如何绑定未绑定的方法,似乎有一个潜在的答案(可能不是最好的)。因此,我们可以这样做:
>>> 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
所以你想要两种方法——例如
Foo.shadowed
和Foo().shadowed
?听起来很像我刚才问的问题(虽然不是重复)。@user2357112:是的,我从你的问题中得出了这个问题。如果这一个有答案,那么出于好奇,我们也可以找到你的答案。你为什么需要这个?@karthikr:为了能够回答-似乎+
操作符正确地查找了阴影方法,我想知道如何“手动”执行相同的操作
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