0

How do you access an instance in an object and pass it to another 'main' object? I'm working with a parser for a file that parses different tags, INDI(individual), BIRT(event), FAMS(spouse), FAMC(children)

Basically there are three classes: Person, Event, Family

class Person():
    def __init__(self, ref):
        self._id = ref
        self._birth : None

    def addBirth(self, event):
        self._birth: event

class Event():
    def __init__(self, ref):
        self._id = ref
        self._event = None

    def addEvent(self, event):
        self._event = event

        #**event = ['12 Jul 1997', 'Seattle, WA'] (this is generated from a     function outside a class)

I want to transfer self._event from the Event class into addBirth method to add it into my person class. I have little knowledge on how classes and class inhertiances work. Please help!

ettanany
  • 19,038
  • 9
  • 47
  • 63
  • Just add an argument to the desired methods and pass it from an appropriate caller? –  Dec 02 '16 at 16:16

2 Answers2

0

If I understand your question, you want to pass an (for example) Event object to an instance of Person?

Honestly, I don't understand the intent of your code, but you probably just need to pass self from one class instance to the other class instance.

self references the current instance.

class Person:
    def __init__(self):
        self._events = []

    def add_event(self, event)
        self._events.append(event)

class Event:
    def add_to_person(self, person):
        person.add_event(self)
0

The most proper way to handle situations like this is to use getter and setter methods; data encapsulation is important in OO programming. I don't always see this done in Python where I think it should, as compared to other languages. It simply means to add methods to your classes who sole purpose are to return args to a caller, or modify args from a caller. For example

Say you have class A and B, and class B (caller) wants to use a variable x from class A. Then class A should provide a getter interface to handle such situations. Setting you work the same:

class class_A():
    def __init__(self, init_args):
        x = 0

    def someMethod():
        doStuff()

    def getX():
        return x

    def setX(val):
        x = val

class class_B():
    def init(self):
        init_args = stuff
        A = class_A(init_args)
        x = class_A.getX()

    def someOtherMethod():
        doStuff()

So if class B wanted the x property of an instance object A of class class_A, B just needs to call the getter method.

As far as passing instances of objects themselves, say if you wanted A to pass an already-created instance object of itself to a method in class B, then indeed, you simply would pass self.

pretzlstyle
  • 2,774
  • 5
  • 23
  • 40