2

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?

4
  • You're setting the attribute on the class object. So __setattr__ is called, but it's called on the metaclass. Look up metaclasses to get an idea of what you're in for. Commented Feb 21, 2017 at 6:14
  • @BrenBarn thanks for the advice, I shall do that soon. However, to solve my immediate problem, do you mind submitting an answer? :) Commented Feb 21, 2017 at 6:23
  • Are you using Python 2 or Python 3? Commented Feb 21, 2017 at 6:35
  • @BrenBarn Python3 Commented Feb 21, 2017 at 6:44

1 Answer 1

7

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.