Handing a number of methods to the same child class

Steven Bethard steven.bethard at gmail.com
Tue Jan 11 02:35:26 EST 2005


Dave Merrill wrote:
> Somewhat silly example:

I know you've hedged this by calling it a "silly" example, but I would 
like to point out that your set_X methods are unnecessary -- since 
Python allows you to overload attribute access, getters and setters are 
generally unnecessary.

> class Address:
>     def __init__():
>         self.displayed_name = ''
>         self.adr = ''
>         self.city = ''
>         self.state = ''
>     def set_name(name):
>         self.displayed_name = name
>     def set_adr(adr):
>         self.adr = adr
>     def set_city(city):
>         self.city = city
>     def set_state(state):
>         self.state = state
> 
> class Phone:
>     def __init__():
>         self.displayed_name = ''
>         self.number = ''
>     def set_name(name):
>         self.displayed_name = name
>     def set_number(number):
>         self.number = number
> 
> class Customer:
>     def __init__():
>         self.last_name = ''
>         self.first_name = ''
>         self.adr = Adr()
>         self.phone = Phone()
>     def set_adr_name(name):
>         self.adr.set_name(name)
>     def set_adr_adr(adr):
>         self.adr.set_adr(adr)
>     def set_adr_city(city):
>         self.adr.set_city(city)
>     def set_adr_state(state):
>         self.adr.set_state(state)
>     def set_phone_name(name):
>         self.phone.set_name(name)
>     def set_phone_number(number):
>         self.phone.set_number(number)
> 
> IOW, all the adr methods go to the corresponding method in self.adr, all the
> phone methods go to self.phone, theorectically etc for other rich
> attributes.
> 
> What I'd really like is to say, "the following list of methods pass all
> their arguments through to a method of the same name in self.adr, and the
> following methods do the same but to self.phone." Is there some sane way to
> express that in python?

py> class Address(object):
...     def __init__(self, city, state):
...         self.city = city
...         self.state = state
...
py> class Customer(object):
...     def __init__(self, name, addr):
...         self.name = name
...         self.addr = addr
...     def __getattr__(self, attr):
...         if attr.startswith('adr_'):
...             return getattr(self.addr, attr[4:])
...         raise AttributeError(attr)
...
py> c = Customer("Steve", Address("Tucson", "AZ"))
py> c.adr_city
'Tucson'
py> c.adr_state
'AZ'

I've used a slightly different example from yours, but hopefully you can 
see how to apply it in your case.  The __getattr__ method is called when 
an attribute of an object cannot be found in the normal locations (e.g. 
self.__dict__).  For all attributes that begin with "adr_", I delegate 
the attribute lookup to the self.addr object instead.

Steve



More information about the Python-list mailing list