Accessing class variables in staticmethods.
Ramashish Baranwal
ramashish.lists at gmail.com
Mon Jan 22 01:12:26 EST 2007
Sam wrote:
> On 21 Jan 2007 12:49:17 -0800, Ramashish Baranwal
> <ramashish.lists at gmail.com> wrote:
> > class Base:
> > staticvar = 'Base'
> >
> > @staticmethod
> > def printname():
> > # this doesn't work
> > # print staticvar
> > # this does work but derived classes wouldn't behave as I want
> > print Base.staticvar
> >
> > class Derived(Base):
> > staticvar = 'Derived'
> >
> > Base.printname() # should print 'Base'
> > Derived.printname() # should print 'Derived'
> >
> > Any idea on how to go about this? Also from a staticmethod how can I
> > find out other attributes of the class (not objects)? Do static methods
> > get some classinfo via some implicit argument(s)?
>
> No, staticmethods get told nothing about the class they're being
> defined in. What you want is a classmethod, which gets passed the
> class to work with.
>
> Using classmethods, your code becomes:
>
> #untested, bear in mind
> class Base:
> staticvar = 'Base'
>
> @classmethod
> def printname(cls):
> print cls.staticvar
>
> class Derived(Base):
> staticvar = 'Derived'
>
> Base.printname() #prints 'Base'
> Derived.printname() #prints 'Derived'
>
> Incidentally, you can also use cls.__name__ for this purpose, but I
> guess that your actual motivation for this is more complicated than
> class names.
Thanks Sam, using classmethod works. You guessed it correctly, my
actual motivation is more complicated but on the same line.
-Ram
More information about the Python-list
mailing list