Help with super()

David Hirschfield davidh at ilm.com
Thu Jan 12 19:58:31 EST 2006


Good point, I did notice that.

My example is total junk, actually. Now that I look at it, it isn't at 
all possible to do what I'm after this way, since _getv() is never going 
to be looking at class A's _v value.

So, the larger question is how to do anything that resembles what I 
want, which is to have a chain of subclasses with a single attribute 
that each subclass can define as it wishes to, but with the ability to 
get the combined value from all the ancestors down to the current 
subclass I access that attribute from.

Does that make any sense?

Something like (and this is totally made-up pseudo-code):

class A:
    v = [1,2]

class B(A):
   v = [2,3]

class C(B):
    v = [4,5]

c = C()
c.getv() ==> [1,2,2,3,4,5]

-Dave

Paul McNett wrote:

> David Hirschfield wrote:
>
>> I tried that and super(B,self), but neither works.
>>
>> Using super(A,self) in the _getv(self) method doesn't work, since the 
>> super() of A is "object" and that doesn't have the v property at all.
>> Not sure why you say that using self.__class__ is wrong as the first 
>> argument to super(), it should be the same as using the class name 
>> itself - both will result in <class blah.B> or whetever self is an 
>> instance of.
>>
>> I still don't see a way to accomplish my original goal, but any other 
>> suggestions you might have would be appreciated.
>
>
> Your basic problem is that property fset(), fget() and friends are 
> defined at the class level, not at the instance level. So if you want 
> to override the setter of a property in a subclass, you pretty much 
> have to redefine the property in that subclass. And therefore, you 
> also have to redefine the getter of the property as well. There is no 
> easy way to "subclass" property getters and setters.
>
> But, there's another problem with your example code as well. You 
> appear to assume that self._v is going to refer to the _v defined in 
> that class. But take a look at this:
>
> class A(object):
>   _v = [1,2,3]
>
>   def _getv(self):
>     print self._v ## hey, look, I'm [4,5,6]!!!
>   v = property(_getv)
>
>
> class B(A):
>   _v = [4,5,6]
>
> b = B()
>
> print b.v
>
>

-- 
Presenting:
mediocre nebula.




More information about the Python-list mailing list