user9159966
user9159966

Reputation:

Why python metaclass is not working in this code?

class My_meta(type):

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

class Just_a_class(metaclass=My_meta):
    pass

a = Just_a_class()
a.hello() 

Above code is giving:

AttributeError: 'Just_a_class' object has no attribute 'hello'

Please suggest the changes to make it work. Thanks.

Upvotes: 0

Views: 60

Answers (1)

Barmar
Barmar

Reputation: 780655

Methods in a metaclass are inherited by the class object, not class instances. You can call the function this way:

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

Upvotes: 1

Related Questions