首页 > 解决方案 > 在Python中更改对象A中另一个对象B的属性

问题描述

假设我有两类对象,A 和 B。两者都在数据库中链接在一起。我们有一个事件和一系列与每个事件相关联的动作,以及每个事件的一些属性。

class Event(object):
    def __init__(self, ...some irrelevant attributes...):
        self.attributes = attributes
        self.actions = []

    def add_action(self, action):
        self.actions.append = action

class Action(object):
    def __init__(self, ...some irrelevant attributes...):
        self.attributes = attributes
        self.event = None

    def add_event(self, event):
        self.event = event
        # I would like to make self part of event.actions as above

当我打电话

event = Event(...)

Action(...)将动作添加到数据库中的事件中,Python 中是否有合法的方式使动作本身(自身)成为事件的动作列表的一部分?

标签: pythonlistattributesselfobject-oriented-database

解决方案


打电话add_action()

    def add_event(self, event):
        self.event = event
        # I would like to make self part of event.actions as above
        event.add_action(self)

另外,您在add_action(). 它应该调用该append()方法,而不是分配给它。

    def add_action(self, action):
        self.actions.append(action)

推荐阅读