【问题标题】:Why python metaclass is not working in this code?为什么 python 元类在这段代码中不起作用?
【发布时间】:2020-01-28 04:24:42
【问题描述】:
class My_meta(type):

    def hello(cls):
        print("hey")

class Just_a_class(metaclass=My_meta):
    pass

a = Just_a_class()
a.hello() 

以上代码给出:

AttributeError: 'Just_a_class' 对象没有属性 'hello'

请提出更改以使其发挥作用。谢谢。

【问题讨论】:

  • 元类与超类不同。实例不从元类继承方法。
  • 为什么你认为Just_a_class 的实例会有那个方法?

标签: python python-3.x metaclass


【解决方案1】:

元类中的方法由类对象继承,而不是类实例。你可以这样调用函数:

Just_a_class.hello()
// or
a = Just_a_class()
a.__class__.hello()

【讨论】:

  • 感谢您的帮助!
猜你喜欢
  • 2015-03-20
  • 2013-03-22
  • 2010-09-18
相关资源
最近更新 更多