Abhishek Divekar
Abhishek Divekar

Reputation: 1247

Python override metaclass set attribute

Suppose I have a class:

class ABC:
    pass

And I do:

ABC.x = 123

This does not give me an error, even though I haven't created an object. Which of the __func__ methods is being called, and how do I override it?

Upvotes: 2

Views: 2833

Answers (1)

BrenBarn
BrenBarn

Reputation: 251373

You need to define a metaclass and override __setattr__ there, then make your class use that metaclass.

class Meta(type):
    def __new__(meta, name, bases, attrs):
        return super().__new__(meta, name, bases, attrs)

    def __setattr__(cls, attr, value):
        print("I am setting {}.{} = {}".format(cls.__name__, attr, value))
        return super().__setattr__(attr, value)

class Foo(metaclass=Meta):
    pass

Then:

>>> Foo.blah = 2
I am setting Foo.blah = 2
>>> Foo.blah
2

Upvotes: 7

Related Questions