classmethods, class variables and subclassing
Andrew Jaffe
a.jaffe-usenet at bakerjaffe.plus.com
Fri Oct 21 18:05:21 EDT 2005
Steven Bethard wrote:
> Andrew Jaffe wrote:
>
> I'm not sure if I understand your goal here, but you can get different
> behavior using super().
>
> py> class sup(object):
> ... cvar1 = None
> ... cvar2 = None
> ... @classmethod
> ... def setcvar1(cls, val):
> ... cls.cvar1 = val
> ... @classmethod
> ... def setcvar2(cls, val):
> ... cls.cvar2 = val
> ... @classmethod
> ... def printcvars(cls):
> ... print cls.cvar1, cls.cvar2
> ...
> py> class sub(sup):
> ... cvar1a = None
> ... @classmethod
> ... def setcvar1(cls, val, vala):
> ... cls.cvar1a = vala
> ... super(sub, cls).setcvar1(val)
> ... @classmethod
> ... def printcvars(cls):
> ... print cls.cvar1a
> ... super(sub, cls).printcvars()
> ...
> py> sub.setcvar1(1, 10); sub.setcvar2(2); sub.printcvars()
> 10
> 1 2
> py> sup.printcvars()
> None None
Aha! This is the behavior I want -- the variables get set correctly when
the methods are called on the subclass. I thought super() might be the
right idea, but I didn't realize you could call it as super(sub, cls)
rather than with an instance in the second slot. I don't think my use
case ever needs the superclass to have the variables accessible as in
your next ideas, not reproduced here.
Thanks!
Andrew
More information about the Python-list
mailing list