python继承 - 引用基类方法

时间:2012-12-15 15:04:26

标签: python class inheritance

# 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

我认为我想要做的很简单,但我从未在Python中处理过继承。我正在尝试的任何东西似乎都没有用。我想要做的是创建一个类,重新定义基类中的一些原始方法,同时仍然能够访问基类中的所有其他方法。在上面的例子中,我希望能够做到这一点:

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

输出将是:

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

我是否遗漏了某些内容,或者它是否应该按照目前的内容编写?

1 个答案:

答案 0 :(得分:4)

是的,它几乎可以正常工作:

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")

我有:

  1. Base
  2. 派生object
  3. 移动Base以显示在Derived;
  4. 之前
  5. 重命名为str,因为它是影子builtin functions;
  6. 的不良形式
  7. 添加了代码以实例化Derived