dumb q: repeated inheritance in python?

Corey Coughlin corey.coughlin at attbi.com
Fri Sep 12 13:54:09 EDT 2003


Thanks Duncan, that's exactly what I needed!  I'm not very familiar
with subclassing properties, I guess I'll play around with it and see
if I can figure it out.  But thanks again, it's great code!

			------ Corey


Duncan Booth <duncan at NOSPAMrcp.co.uk> wrote in message news:<Xns93F467BCD2CA5duncanrcpcouk at 127.0.0.1>...
> corey.coughlin at attbi.com (Corey Coughlin) wrote in 
> news:a8623416.0309111319.14334945 at posting.google.com:
> 
> >  What I'd really like to do is inherit this same object
> > twice, but the second time rename the objects so that I get 'name2'
> > instead of 'name'.  (And somehow rename the functions, and so on.)
> 
> I'm not sure if I exactly understood what you want, but does this help?
> I think you are asking for two properties that access differently named 
> attributes but perform the same type checking in each case. 
> 
> That sounds to me like you want a specialised property which can be done by 
> subclassing it:
> 
> ---- begin test.py ----
> class Name(property):
>     def __init__(cls, attrname):
>         
>         def setnm(self, nm):
>             if isinstance(nm, str):
>                 setattr(self, attrname, nm)
>             else:
>                 raise TypeError("Name passed to %s isn't a string" % 
> self.__class__.__name__)
> 
>         def getnm(self):
>             return getattr(self, attrname)
> 
>         property.__init__(cls, getnm, setnm)
> 
> 
> class TwoNamed(object):
>     def __init__(self, iname='', jname=''):
>         self.iname, self.jname = iname, jname
> 
>     name = Name('iname')
>     name2 = Name('jname')
> 
> x = TwoNamed('ivalue', 'jvalue')
> print "name, name2 =",x.name, x.name2
> 
> x.name = 'www'
> x.name2 = 'xxx'
> 
> print "name, name2 =",x.name, x.name2
> print "iname, jname =",x.iname, x.jname
> 
> x.name = 42 # Blows up
> print x.name # Never reached.
> ----- end of test.py ----




More information about the Python-list mailing list