【发布时间】:2016-05-10 03:39:48
【问题描述】:
在 Python 中工作,如何通过它实例化的类来检索元类(元方法)拥有的方法?在以下场景中,这很简单——只需使用getattr 或点表示法:
* 所有示例都使用版本安全的with_metaclass
class A(type):
class A(type):
"""a metaclass"""
def method(cls):
m = "this is a metamethod of '%s'"
print(m % cls.__name__)
class B(with_metaclass(A, object)):
"""a class"""
pass
B.method()
# prints: "this is a metamethod of 'B'"
但这很奇怪,因为在dir(B) 的任何地方都找不到'method'。由于这个事实,动态覆盖这样的方法变得很困难,因为元类不在super 的查找链中:
class A(type):
"""a metaclass"""
def method(cls):
m = "this is a metamethod of '%s'"
print(m % cls.__name__)
class B(with_metaclass(A, object)):
"""a class"""
@classmethod
def method(cls):
super(B, cls).method()
B.method()
# raises: "AttributeError: 'super' object has no attribute 'method'"
那么,正确覆盖元方法的最简单方法是什么?我已经对这个问题提出了自己的答案,但期待任何建议或替代答案。提前感谢您的回复。
【问题讨论】: