Class Creation Decommission

Asked 2 years ago, Updated 2 years ago, 15 views

class cls:

    log = []

    def __init__(self, name):
        self.name = name    
        print (self.name + "Create.")

    def add(self, val):    
        self.log.append(val)    

    def __del__(self):
        self.log.clear() ################################## This part
        print (self.name + "disappear")

logs = []

mycls = cls('a1')

mycls.add("aa1")

logs.append(mycls.log)


mycls = cls('b1')

mycls.add("bb2")

logs.append(mycls.log)


print(logs)

In the above code, you want to save only aa1 and bb2 in logs.
If you delete the part #### above, it is saved as aa1, bb2 aa1, and bb2.
Maybe because I'm a C# developer, I don't think there should be self.log.clear().
Master, please.

python

2022-09-20 20:13

1 Answers

If you look at the code you wrote, there is no self on the log in cls.

If you write it like this, log is not an instance variable, but a class variable, which is shared by all instances.

This means that if you overwrite the new instance in mycls, the class variable log remains.

Therefore, if you add a new value to the corresponding log, it will be added after the existing value.

When you run logs.append(mycls.log), the two values are always the same because the list named logs is duplicated with a list pointing to the same address.

Move the log into __init__ and put self in front of it to operate in the desired form.


2022-09-20 20:13

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.