有没有办法访问 python 中另一个对象的属性

Is there a way to access the attribute of another object in python

我正在尝试创建三个 classes,一个主要存储一个人的属性,另外两个将访问一个人的实例并执行一系列操作来调整其属性值。

我想将它们分开放置,以便于管理每个 class 中的内容并进行扩展。我认为这不是继承问题,所以我的代码对于目标来说显然是错误的,但我不知道应该做什么。


class CreatePerson():
    def __init__(self):
        self.to_do_list=[]

class Shop(CreatePerson):
    def __init__(self,CreatePerson):
        super().__init__()
    def add_element(self,a):
        self.to_do_list+=[a]


class Recreation(CreatePerson):

    def __init__(self,CreatePerson):
        super().__init__()

    def add_element(self,a):
        self.to_do_list+=[a]


if __name__ == '__main__':

    joe=CreatePerson()
    p1=Shop(joe)
    p2=Recreation(joe)
    p1.add_element('whole milk')
    p2.add_element('reading book')
    print(joe.to_do_list)

我希望它可以 return 跟随,但显然它没有 link

['whole milk','reading book']

如果我理解正确,您希望 ShopRecreation 对象共享其基础 CreatePerson 对象。但是您的代码不会那样做。正如 @mike scotty 评论的那样,您传入 Joe,但不要将 Joe 用于任何用途。所以这些新对象只是创建了它们自己的 to_do_lists,它们并不共享。这是我想象中你想要的东西:

class CreatePerson():
    def __init__(self):
        self.to_do_list = []
    def add_element(self, a):
        self.to_do_list += [a]


class Shop():
    def __init__(self, CreatePerson):
        self.my_person = CreatePerson
    def add_element(self, a):
        self.my_person.add_element(a)


class Recreation():
    def __init__(self, CreatePerson):
        self.my_person = CreatePerson
    def add_element(self, a):
        self.my_person.add_element(a)

>>> joe=CreatePerson()
>>> p1=Shop(joe)
>>> p2=Recreation(joe)
>>> p1.add_element('whole milk')
>>> p2.add_element('reading book')
>>> print(joe.to_do_list)
['whole milk', 'reading book']

所以现在 Shop 和 Recreation 不是 CreatePerson 的实例,但它们确实在其构造函数中采用 CreatePerson,并存储对该人的引用。当您对这些对象调用 add_element 时,它们会调用其 CreatePerson 具有的新 add_element 方法。

我只是想指出,我认为这不是完全正确的抽象 - 您的商店只有一个人,您的娱乐活动也是如此。但为了回答这个问题,我是按字面意思理解的。

希望对您有所帮助,编码愉快!