Virtual access of class attribute from within the class

Alex Martelli aleax at aleax.it
Tue Feb 25 14:22:20 CET 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 )

A staticmethod is never "virtual" in Python, just as it can never
be in C++ of course.  What you need is indeed a classmethod instead:

      def setHello(cls, x):
          cls.hello = x * x
      setHello = classmethod(setHello)

> class B( A ):
>     hello = None      # Without this statement B.hello will be A.hello!

Note that, even without this statement, when you call B.setHello(10)
B.hello *IS* specifically assigned separatel from 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

Not *static* methods specifically.  That's exactly the point of the
distinction between static and class methods.

You can OVERRIDE the static method in B (that's what "virtual" normally
means in C++ -- a method you can override), and in this sense I guess
it's virtual too.  But if you want magic class-specific behavior
WITHOUT overriding the method, then it's a classmethod you need.


Alex





More information about the Python-list mailing list