python继承-引用基类方法

python继承-引用基类方法,python,class,inheritance,Python,Class,Inheritance,我认为我想做的很简单,但我从未在Python中处理过继承问题。我所尝试的一切似乎都不管用。我想做的是创建一个类,重新定义基类中的一些原始方法,同时仍然能够访问基类中的所有其他方法。在上面的示例中,我希望能够做到这一点: # Derived class that inherits from Base class. Only one of the # parent methods should be redefined. The other should be accessible # by ca

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

# 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
结果是:

derived_obj.result("test")
derived_obj.info("test2")
我是否遗漏了一些东西,或者应该按照当前编写的方式来完成此工作?

是的,它将(几乎)按原样工作:

我有:

  • 对象
    导出
    基础
  • 移动了
    Base
    以显示在
    派生的
    之前
    
  • 重命名为
    str
    ,因为阴影的形式不好
  • 添加了实例化
    派生
    的代码
  • 是的,它将(几乎)按原样工作:

    我有:

  • 对象
    导出
    基础
  • 移动了
    Base
    以显示在
    派生的
    之前
    
  • 重命名为
    str
    ,因为阴影的形式不好
  • 添加了实例化
    派生
    的代码

  • 它应该按照您写下的方式工作(前提是您先定义
    Base()
    )。你到底看到了什么问题?老实说,我甚至不知道如何实例化对象。我已经读了足够多的书,知道如何定义类,但我不知道下一步该怎么做。它应该按照您写的那样工作(前提是您先定义
    Base()
    )。你到底看到了什么问题?老实说,我甚至不知道如何实例化对象。我已经读了足够多的书,知道如何定义类,但我不知道下一步该怎么做。太棒了。非常感谢。我现在明白Martijn在评论我原来的帖子时的意思了。另外,谢谢你在第三章中的提示。太棒了。非常感谢。我现在明白Martijn在评论我原来的帖子时的意思了。另外,谢谢第三部分的提示。
    Derived String (result): test
    Base String (info): test2
    
    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")