Nested Classes and Instances
J. Cliff Dyer
jcd at sdf.lonestar.org
Fri Jul 10 16:12:11 EDT 2009
On Fri, 2009-07-10 at 19:00 +0200, Manuel Graune wrote:
> Hello,
>
> as an example of what I would like to achieve, think of a street
> where each house has a door and a sign with a unique (per house)
> number on it. I tried to model this like this:
>
> class House(object):
> class Door(object):
> def __init__(self,color):
> self.color=color
> class Sign(object):
> def __init__(self,text):
> self.text=text
> def __init__(self, doorcolor,housenumber):
> self.housenumber=housenumber
> self.door=House.Door(doorcolor)
> self.sign=House.Sign(housenumber)
>
> house1=House("red","1")
> house2=House("blue","2")
>
Don't do it like that. Keep your classes independent. Many houses can
have doors, and there's no reason to redefine the concept of Doors for
each one. Same goes for Signs.
class House(object):
def __init__(self, doorcolor, housenumber):
self.door = Door(doorcolor)
self.sign = Sign(housenumber)
self.number = housenumber
class Door(object):
def __init__(self, color):
self.color = color
class Sign(object):
def __init__(self, inscription):
self.inscription = str(housenumber)
(Something like that)
Cheers,
Cliff
> Well, so far, so good. Now, what I'd like to achive is that the text of
> the "sign" changes whenever the variable "housenumber" of the
> "parent-instance" changes or that
> "house1.sign.text" is a reference/pointer to "house1.housenumber"
>
> Thanks in advance,
>
> Manuel
>
>
>
> --
> A hundred men did the rational thing. The sum of those rational choices was
> called panic. Neal Stephenson -- System of the world
> http://www.graune.org/GnuPG_pubkey.asc
> Key fingerprint = 1E44 9CBD DEE4 9E07 5E0A 5828 5476 7E92 2DB4 3C99
More information about the Python-list
mailing list