I’d like to set a class property that can be shared by all instances of the class or its subclasses. It should be possible for any instance to also set the property.
I tried the following:
class A:
x = 1
@classmethod
def setX(cls, val):
if cls.__bases__:
cls = cls.__bases__[-1]
cls.x = val
This seems to work fine in case of single inheritance. But if I use multiple inheritance, depending on the order of inheritance, it either works or doesn’t (i.e., class A is not always the last of bases).
Any ideas for a robust implementation?
The right way, IMO, is to go with a class property. Since properties are tied to an object’s classes
__dict__, as opposed to the object’s very own__dict__, and since your object happens to be a class, you must attach it to the classes class, its metaclass:Result:
Also, your classes must be new style classes, i.e. they must inherit from
objectin Python 2.x. And metaclasses are defined differently in Python 3.x: