Nested Classes and Instances

Peter Otten __peter__ at web.de
Fri Jul 10 13:37:15 EDT 2009


Manuel Graune wrote:

> 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")
> 
> 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"

Python doesn't support C-style pointers, but you can work around it to some 
degree:

>>> class House(object):
...     def __init__(self, housenumber):
...             self.housenumber = housenumber
...             self.sign = Sign(self)
...
>>> class Sign(object):
...     def __init__(self, house):
...             self.house = house
...     @property
...     def text(self): return self.house.housenumber
...
>>> house = House(42)
>>> house.sign.text
42
>>> house.housenumber = "42b"
>>> house.sign.text
'42b'

If you are concerned about the tight coupling between House and Sign you can 
modify Sign to accept a function that gets the housenumber:

>>> class House(object):
...     def __init__(self, n): self.housenumber = n
...
>>> class Sign(object):
...     def __init__(self, gettext):
...             self._gettext = gettext
...     @property
...     def text(self): return self._gettext()
...
>>> house = House(7)
>>> house.sign = Sign(lambda house=house: house.housenumber)
>>> house.sign.text
7

Peter




More information about the Python-list mailing list