0
# Derived class that inherits from Base class. Only one of the 
# parent methods should be redefined. The other should be accessible
# by calling child_obj.parent_method().
class Derived(Base):
    def result(self,str):
        print "Derived String (result): %s" % str

# Base class that has two print methods
class Base():
    def result(self,str):
        print "Base String (result): %s" % str

    def info(self,str):
        print "Base String (info): %s" % str

I think what I want to do is simple, but I've never dealt with inheritance in Python. Nothing I'm trying seems to work. What I want to do is create a class that redefines a handful of the original methods in the base class while still being able to access all of the other methods in the base class. In the above example, I would want to be able to do this:

derived_obj.result("test")
derived_obj.info("test2")

And the output would be this:

Derived String (result): test
Base String (info): test2

Am I missing something or should this work as it's currently written?

4

1 に答える 1

4

Yes, it'll work (almost) as-is:

class Base(object):

    def result(self, s):
        print "Base String (result): %s" % s

    def info(self, s):
        print "Base String (info): %s" % s

class Derived(Base):

    def result(self, s):
        print "Derived String (result): %s" % s

derived_obj = Derived()
derived_obj.result("test")
derived_obj.info("test2")

I have:

  1. derived Base from object;
  2. moved Base to appear before Derived;
  3. renamed str since it's bad form to shadow builtin functions;
  4. added code to instantiate Derived.
于 2012-12-15T15:07:25.177 に答える