[Tutor] properties and subclasses

Brian van den Broek bvande at po-box.mcgill.ca
Tue Apr 26 00:36:00 CEST 2005


Hi all,

I'm trying to get a hang of properties. It isn't quite clear to me
what is the best way to make properties differ in subclasses. Some
code snips to show what I've tried:

>>> class A(object):
... 	def __init__(self): pass
... 	def prop_set(self): return "I was set by A's method"
... 	my_property = property(prop_set)
... 	
>>> class AA(A):
... 	def __init__(self): pass
... 	def prop_set(self): return "I was set by AA's method"
... 	
>>> aa = AA()
>>> aa.my_property
"I was set by A's method"

OK, so the naive approach didn't work -- I wanted aa.my_property to be
"I was set by AA's method".


So, the next thought was to change A's my_property assignment:

>>> class A(object):
... 	def __init__(self): pass
... 	def prop_set(self): return "I was set by A's method"
... 	my_property = property(self.prop_set)
...
Traceback (most recent call last):
...
NameError: name 'self' is not defined

OK, that worked less well, still :-)


I can get what I want this way:

>>> class A(object):
... 	def __init__(self): pass
... 	def prop_set(self): return "I was set by A's method"
... 	my_property = property(prop_set)
...
>>> class AA(A):
... 	def __init__(self): pass
... 	def prop_set(self): return "I was set by AA's method"
... 	my_property = property(prop_set)
...
>>> aa = AA()
>>> aa.my_property
"I was set by AA's method"

But the reduplication of the prop_set definition and the my_property
assignment line seem to go against the grain of OOP to me.


The best I have manged to date is:

>>> class B(object):
... 	def __init__(self): pass
... 	def prop_set(self): return self.property_setter()
... 	def property_setter(self): return "I was set by a B method"
... 	my_property = property(prop_set)
...
>>> class BB(B):
... 	def __init__(self): pass
... 	def property_setter(self): return "I was set by a BB method"
...
>>> b=B()
>>> b.my_property
'I was set by a B method'
>>> bb=BB()
>>> bb.my_property
'I was set by a BB method'
>>>

Is that the cleanest way available? The indirection doesn't bother me
too much, but it feels like it might have bothered Guido et. al. 
enough that I worry I am missing a better approach.

Further, are my desired indicative of a misunderstanding of the role
of properties?

I'd aimed to make a separate post explaining why this matters to me 
and asking for alternative solutions, but the draft I have yet to 
finish is rather more dense than this post. So, I will leave off 
unless respondents think it matters to the current enquiry.

Thanks and best to all,

Brian vdB




More information about the Tutor mailing list