super and classmethod
Here's a nice example of why you have to use super in order for classmethod to work correctly in derived classes.
The code:
class Base(object):
@classmethod
def method(cls):
print 'In base: ', cls.__name__
print
class DerivedWithoutSuper(Base):
@classmethod
def method(cls):
print 'In derived:', cls.__name__
Base.method()
class DerivedWithSuper(Base):
@classmethod
def method(cls):
print 'In derived:', cls.__name__
super(DerivedWithSuper, cls).method()
if __name__ == '__main__':
DerivedWithoutSuper().method()
DerivedWithSuper().method()
The output:
$ python super_classmethod.py In derived: DerivedWithoutSuper In base: Base In derived: DerivedWithSuper In base: DerivedWithSuper
Tags: python
Tue, 18 Sep 2007 16:05 UTC
About This Blog
This is the personal blog of Christopher Stawarz, a software developer who lives and works in Cambridge, Massachusetts.
The design of this site is a slightly-modified version of Typography Paramount, an open-source web design template created by Six Shooter Media and available at Open Designs. The pages are statically rendered by a custom Python script, which uses docutils to convert reStructuredText input files to XHTML, Pygments to add syntax highlighting to code examples, and Cheetah templates to generate the output files.