Change attribute of another object B within object A in Python

669 views Asked by At

Suppose I have two classes of objects, A and B. Both are linked together in a database. We have an Event and a series of Actions associated with each event, and some attributes of each.

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

When I call

event = Event(...)

in Action(...) to add Action to an event in a database, is there a legal way in Python to make the Action itself (self) part of Event's list of Actions?

2

There are 2 answers

0
Barmar On

Just call 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)

Also, you have a mistake in add_action(). It should call the append() method, not assign to it.

    def add_action(self, action):
        self.actions.append(action)
0
Daniel On

you should call add_action with self. you should also change the way you append to your list of actions. the append attribute of a list is a 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)