Home > Software design >  Why is the list in the class attribute still a class attribute after instantiation, not an instance
Why is the list in the class attribute still a class attribute after instantiation, not an instance

Time:10-19

I have a class with a property and a list with empty values. When two instances of a and b are generated and elements are added to the property, it is found that the property is not instantiated. Use id to view a.property and b.property. The memory address is the same. Why?

How can the property attribute become an instance attribute?

My code example is as follows:

class MyClass:
    property = []

    def __init__(self):
        pass

    def append(self, value):
        self.property.append(value)


a = MyClass()
b = MyClass()
a.append(1)
print(a.property)
b.append(1)

print(a.property)
print(b.property)

print(id(a.property))
print(id(b.property))

The result is:

[1]
[1, 1]
[1, 1]
1866383694784
1866383694784

The result I respected:

[1]
[1]
[1]

CodePudding user response:

In your case property = [] is a class variable, which is shared with all instances of your class. I asume, that you don't want to share the value of property = [] with other classes. That means you need a instance variable, which can be defined like down below.

class MyClass:
    def __init__(self):
        self.property = []

    def append(self, value):
        self.property.append(value)

This should give you your expected output, sheers!

CodePudding user response:

It happens because you don't declare property inside of the __init__ function.
__init__ is being called every time a new instance of the object is created, so I guess this is what you are looking for.
Try applying the following changes to your class:

class MyClass:
    def __init__(self):
        self.property = []

    def append(self, value):
        self.property.append(value)
  • Related