Is it possible, somehow in python, to create attributes in a class that is common to all objects?

Asked

Viewed 87 times

0

Is it possible, somehow in python, to create attributes in a class that is common to all objects? And somehow if it is changed during the execution of the program change to all objects already created? The closest I saw was to directly change the attribute in the class

class Teste:
    a = 0

.

>>>b = Teste()
>>>c = Teste()
>>>Teste.a = 10

In this case for both "b" and "c" the value of "a" would be 10 But if I changed the value of "a" to "b" or "c" individually before changing directly in the class, this would not occur. As shown below:

class Teste:
    a = 0

.

>>>b = Teste()
>>>c = Teste()
>>>b.a = 5
>>>Teste.a = 10

In this case the value of "a" in "c" would be changed to 10, but the value of "a" in "b" would still be 5 and would not be changed to 10 either. Thank you in advance

  • And why does it need to be changed by the object? You cannot simply, when changing, change only by the class?

1 answer

1

In the language itself, you do not have this feature. To access a class variable, you must be explicit.

Have some alternatives to abstract to some extent: properties and use __class__ to not need to say the class name.

class Bla:
        _a = 1
        def get_a(self):
                return Bla._a
        def set_a(self, v):
                Bla._a = v
        a = property(get_a, set_a)

x = Bla()
y = Bla()
x.a = 2
print(y.a)            # deve imprimir 2
x.__class__._a = 3 
print(y.a)            # deve imprimir 3

If there are many static variables to "hide" in this way, you could go to an implementation of getattr() and setattr().

class Bla:
        class_vars = {"a": 1}
        def __getattr__(self, name):
                print("getattr %s" % name)
                return self.__class__.class_vars[name]
        def __setattr__(self, name, value):
                print("setattr %s =" % name, value)
                self.__class__.class_vars[name] = value

x = Bla()
y = Bla()
print(y.a)
x.a = 2
print(y.a)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.