0

this morning a encountered a strange behavior of python's objects (version 3.10.5). Maybe I am doing something wrong and I'd like to know what. Here's a mocked version of my issue :

class MyObject:
    list_of_subobjects = []
    name = ""

    def __init__(self, name):
        self.name = name

    def add_subobject(self, subobject_to_add):
        self.list_of_subobjects.append(subobject_to_add)

    def see_all_subobjects(self):
        print(f"In '{self.name}' there are {len(self.list_of_subobjects)} objects :")
        for subobject in self.list_of_subobjects:
            print(subobject.name)
        
objectA = MyObject("a")
objectB = MyObject("b")
objectC = MyObject("c")

objectA.add_subobject(objectB)
objectB.add_subobject(objectC)

objectA.see_all_subobjects()
# returns : 
# In 'a' there are 2 objects :
# b
# c

In my issue the object "MyObject" is a directory that can contain subdirectories containing subdirectories and so on. The directory B is added to A, then we add a directory C inside B. We should only see B when we ask which directories are directly contained by A, but the scripts outputs B and C. Is it because I add C inside B only after B is added inside A?

Thanks!

1
  • 2
    list_of_subobjects here is a class variable (shared by all instances of MyObject), not an instance variable. Commented Jul 3, 2023 at 9:29

2 Answers 2

1

You need to move the definition of list_of_subobjects = [] and name inside the constructor (__init__()). Otherwise these two fields are class variables, i.e., they are shared by all instances.

This is explained in the documentation with a very similar example.

Sign up to request clarification or add additional context in comments.

Comments

1
class MyObject:
    def __init__(self, name):
        self.list_of_subobjects = []
        self.name = name

1 Comment

list_os_subobjects should not be cls variable

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.