Let’s say I have a class in Python:
class Foo(object):
a = 1
b = 2
I’d like to do some extra stuff when I access ‘a’ but NOT ‘b’. So, for example, let’s assume that the extra stuff I’d like to do is to increment the value of the attribute:
> f = Foo()
> f.a # Should output 2
> f.a # Should output 3
> f.a # Should output 4
> f.b # Should output 2, since I want the extra behavior just on 'a'
It feels like there is a way through __getattr__ or __getattribute__, but I couldn’t figure that out.
The extra thing can be anything, not necessarily related to the attribute (like print ‘Hello world’).
Thanks.
What you are looking for is a property, which can be used nicely as a decorator:
The function is called whenever you try to access
foo_instance.a, and the value returned is used as the value for the attribute. You can also define a setter too, which is called with the new value when the attribute is set.This is presuming you want the odd set-up of class attributes you only ever access from instances. (
_aandbhere belong to the class – that is, there is only one variable shared by all instances – as in your question). A property, however, is always instance-owned. The most likely case is you actually want:Where they are instance attributes.