如何让一个类中的一个对象在python中修改同一个类中的另一个对象?

2024-06-07 08:47:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python中有一个类,我希望能够对一个对象执行一个操作,并让该操作依次标识另一个要更改的对象,然后修改它。要使其具体化:

假设我们有一堆位置(对象),每个位置都有一些东西(称为元素)。我想告诉位置1将它的一个元素向右移动location.move_right(element)。然后它应该将该元素添加到位置2(在我的实际问题中,“位置”需要计算它将移动到哪个位置,所以我不知道它将要去哪里。)

这是我的工作代码。在类中,我放置了一个字典,它将保存所有已创建的对象。我可以想象这会给垃圾收集等带来麻烦。我怀疑有更好的方法。有吗

class location(object):
    locations = {}
    def __init__(self, coordinate):
        self.locations[coordinate]=self
        self.coord = coordinate
        self.elements = set()

    def add_element(self, element):
        self.elements.add(element)

    def move_right(self, element):
        self.elements.remove(element)
        new_location = self.locations[self.coord+1]
        new_location.add_element(element)

x = location(1)
y=location(2)
x.add_element('r')
x.move_right('r')

Tags: 对象selfrightadd元素coordinatenewmove

热门问题