Python - how to reference one object to another

more basic issues I'm struggling with ...

Give the basic code below ... how the object of the object gets 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') 
+4
source share
4 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) 
+6
source

However you want to. Perhaps the easiest way:

 s.address = hm 

But you do not say what you mean by "application." If you need something more complex (for example, if you want the address to be created when creating the Person object), you will need to explain more.

+1
source

you always bind it by assigning it (actually updating the 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 will be exactly the same, but you will be sure that you have an address attribute and you can always have default arguments without any values, for example

 def __init__(self,fn,ln,my_address=None) : ... 
+1
source

As BrenBam asks, what do you mean by application. You should ask yourself how much data you say, how much you need it. I see that you are separating the address class from the person class. This means that these various objects will be used in differentiating ways.

You should be aware of the general principles of database design and why you would share an address from a person or, conversely, why don't you do it.

eg:

 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 the best solution for an address with a lot of people on it or people who move a lot, or for applications that donโ€™t care about who lives or works at the address, namely that there are several of them, each of which deserves attention . some very important junk mail that should inspire them to your products. An application for sending military units would be beneficial as people and people move everywhere.

+1
source

All Articles