Virtual access of class attribute from within the class
Anton Muhin
antonmuhin at sendmail.ru
Tue Feb 25 10:31:31 EST 2003
Stefan Quandt wrote:
> How can I access a class attribute (or class method)
> from within the class in a virtual way, so that in a derived class
> the the member of the derived class will be accessed?
>
> Here is a non-working example to explain what I mean:
>
> class A( object ):
> hello = None
> def __init__( self ):
> pass
> def _setHello( x ):
> A.hello = x * x # How can this assignment be made virtual?
> setHello = staticmethod( _setHello )
>
> class B( A ):
> hello = None # Without this statement B.hello will be A.hello!
> pass
>
> B.setHello( 10 ) # Here B.hello shall be set
> print A.hello, B.hello # (but of course is not).
>
> Since python is an oo language and all members ar virtual, there should be
> a simple way to achieve that.
> Who knows how?
>
> - Stefan
Actually, another solution might work:
class A:
def myHello(self):
return "hello"
class B(A):
def myHello(self):
return "B's hello"
It should work, if you need hello from non-static methods or static
methods with object passed. BTW, it seems that you choosen wrong design,
if you need something like this
Another approach, that should work:
B.hello = something # :)
HTH,
Anton
More information about the Python-list
mailing list