Re: A superclass using a child classes' methods



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.
hell no, this works for methods as well.
Is that right? For attributes I found this example,
where the alphabet attribute is set in the child, but used in the
parent.

http://www.pasteur.fr/formation/infobio/python/ch19s04.html

Should I just set an attribute in the child class and then call the
super's functionality making is pull the data from the attribute?

Thanks,
-kurt
class Parent:
def foo(self):
raise NotImplementedError() # virtual method, it has to be overriden by childs

def bar(self):
self.foo()

class Son(Parent):
def foo(self):
print "I'm your son"

class Daughter(Parent):
def foo(self):
print "I'm your daughter"

Son().bar()
"I'm your son"

Declaring the foo method at the Parent level is not required. But it's a good practice: explicit > implicit and it helps to write proper documentation.

Jean-Michel
.



Relevant Pages

  • instance attributes not inherited?
    ... def __init__: self.x = 9 ... 'Child' object has no attribute 'x' ... If I create an instance of a Child object, I expect it to *be* a Parent object. ... Just washed 9 dishes. ...
    (comp.lang.python)
  • Re: instance attributes not inherited?
    ... Nothing's wrong with python's oop inheritance, you just need to know that the parent class' __init__ is not automatically called from a subclass' __init__. ... def __init__: super.__init__ ... 'Child' object has no attribute 'x' ...
    (comp.lang.python)
  • Re: OOP: method overriding works in mysterious ways?
    ... > class Parent(Grand_parent): ... > def speak(self): ... > def advise: ... > class Child(Parent): ...
    (comp.lang.python)
  • Re: Setting class variable from parent class?
    ... I'm trying to teach my Parent class how to set variables into its Child ... def self.set_my_class_variable ...
    (comp.lang.ruby)
  • A superclass using a child classes methods
    ... I'd like the parent class to have an encode function ... that uses each of the child classes' packing methods. ...
    (comp.lang.python)