A superclass using a child classes' methods
Michael Torrie
torriem at gmail.com
Wed Jun 24 11:49:07 EDT 2009
Kurt Schwehr wrote:
> I'm trying to build an OO system for encoding and decoding
> datapackets. I'd like the parent class to have an encode function
> that uses each of the child classes' packing methods. It appears that
> this works for attributes of children accessed by the parent, but not
> for methods. Is that right? For attributes I found this example,
> where the alphabet attribute is set in the child, but used in the
> parent.
There is no difference between an attribute and a method. They are both
attributes. One happens to be callable and is a method call.
I just tried it and it seemed to work fine. In my old C++ days, I
believe you would call this scenario virtual classes. In python, since
everything is dynamic and computed at runtime, I think you can just
refer to any attribute in the instance and as long as someone down the
road provides it, it would work.
For example:
class parent(object):
def test(self):
print self.child_attribute
self.child_method()
class child(parent):
def __init__(self):
self.child_attribute = 'child'
def child_method(self):
print 'child method is called'
c=child()
c.test()
This should display "child" and "child method is called"
More information about the Python-list
mailing list