【问题标题】:Change attribute of another object B within object A in Python在Python中更改对象A中另一个对象B的属性
【发布时间】:2021-08-30 22:24:17
【问题描述】:

假设我有两类对象,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(...) 中将Action 添加到数据库中的事件中,Python 中是否有合法的方式使Action 本身(自身)成为Event 的Action 列表的一部分?

【问题讨论】:

    标签: python list attributes self object-oriented-database


    【解决方案1】:

    只需拨打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)
    

    【讨论】:

      【解决方案2】:

      您应该使用self 致电add_action。您还应该更改附加到操作列表的方式。列表的append 属性是function

      class Event(object):
          def __init__(self, attributes):
              self.attributes = attributes
              self.actions = []
      
          def add_action(self, action):
              self.actions.append(action)
      
      
      class Action(object):
          def __init__(self, attributes):
              self.attributes = attributes
              self.event = None
      
          def add_event(self, event):
              self.event = event
              event.add_action(self)
      

      【讨论】:

        最近更新 更多