Python嵌套对象

huangapple go评论71阅读模式
英文:

Python nested objects

问题

今早我遇到了Python对象(版本3.10.5)的一个奇怪行为。也许我做错了什么,我想知道是什么问题。以下是我问题的模拟版本:

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()
# 返回:
# In 'a' there are 2 objects :
# b
# c

在我的问题中,对象"MyObject"是一个目录,可以包含子目录,子目录等。将目录B添加到A,然后在B内添加目录C。当我们询问直接包含在A中的目录时,我们应该只看到B,但脚本输出B和C。这是因为我是在将B添加到A内之后才将C添加到B内吗?

谢谢!

英文:

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

得分: 1

需要将list_of_subobjects = []name的定义移到构造函数(__init__())内部。否则,这两个字段将成为类变量,也就是说它们会被所有实例共享。

这在文档中有解释,其中有一个非常相似的示例。

英文:

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.

答案2

得分: 1

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

huangapple
  • 本文由 发表于 2023年7月3日 17:26:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76603461.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定