简体   繁体   English

python继承-引用基类方法

[英]python inheritance - referencing base class methods

# 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. 我想我想做的很简单,但是我从来没有处理过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? 我是否缺少某些东西,还是应该按照目前的方式工作?

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 ; 源自object Base ;
  2. moved Base to appear before Derived ; Base移到Derived之前;
  3. renamed str since it's bad form to shadow builtin functions ; 重命名了str因为它对影子内置函数不利;
  4. added code to instantiate Derived . 添加了代码以实例化Derived

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM