Reputation: 81
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')
Upvotes: 5
Views: 11040
Reputation: 15379
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)
Upvotes: 9
Reputation: 5579
As BrenBam askes, by what do you mean by attach. You should ask yourself how much data are you talking about, how reliable you need it. I see you seperate the address class from the person class. This implies these different objects will be used in differentiating ways.
You should be aware of common database design practices and why you would seperate the address from the person or conversely why you wouldn't.
for example:
addresses = {}
persons = {}
records = {}
address = Address(...)
person1 = Person(...)
person2 = Person(...)
addresses[address.uid] = address
persons[person1.uid] = person1
persons[person2.uid] = person2
records[address.uid] = [person1.uid, person2.uid]
This is a better solution for address with lots of people at it, or people that move around alot, or for apps that don't care who lives or works at an address, just that there is a number of them each deserving of some very important junk mail needing to inspire them for your products. A military troop mailing app would benefit as things and people move all over the place.
Upvotes: 1
Reputation: 1400
you cound always attach it by assigning to it (which would in fact update an internal dict dictionnary of your instace)
s.address = hm
print s.address
>>> <object Address ...>
Or better, do it from within your constructor, namely
class Person :
def __init__(self,fn,ln,my_address) :
[... snip]
self.address = my_address
which is exactly the same, but you will be sure you have an address attribute and can always have default arguments for no values, such as
def __init__(self,fn,ln,my_address=None) : ...
Upvotes: 1
Reputation: 251383
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.
Upvotes: 1