Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - how to reference one object to another

Tags:

python

class

more basic questions i'm struggling with...

Give the basic code below... how does the person object get the address "attached" to it.

class Person(object):
    def __init__(self, fn, ln):
        self.uid    = Id_Class.new_id("Person")
        self.f_name = fn
        self.l_name = ln

class Address(object):
    def __init__(self, st, sub):
        self.uid    = Id_Class.new_id("Address")
        self.street = st
        self.suburb = sub

s = Person('John', 'Doe')

hm = Address('Queen St.', 'Sydney')
like image 336
AtomicCrash Avatar asked Jul 17 '12 20:07

AtomicCrash


2 Answers

Try:

class Person(object):
    def __init__(self, fn, ln, address):
        self.uid    = Id_Class.new_id("Person")
        self.f_name = fn
        self.l_name = ln
        self.address = address

class Address(object):
    def __init__(self, st, sub):
        self.uid    = Id_Class.new_id("Address")
        self.street = st
        self.suburb = sub

hm = Address('Queen St.', 'Sydney')

s = Person('John', 'Doe', hm)
like image 68
Daniel Li Avatar answered Sep 22 '22 19:09

Daniel Li


However you want. Perhaps the simplest way is:

s.address = hm

But you don't say what you mean by "attach". If you want something more elaborate (e.g., if you want the address to be created when the Person object is created) then you'll need to explain more.

like image 29
BrenBarn Avatar answered Sep 23 '22 19:09

BrenBarn