为什么python metaclass在此代码中不起作用?

时间:2019-09-27 21:12:20

标签: python python-3.x metaclass

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”

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

1 个答案:

答案 0 :(得分:1)

元类中的方法是由类对象而不是类实例继承的。您可以通过以下方式调用该函数:

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