繁体   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

我想我想做的很简单,但是我从来没有处理过Python的继承问题。 我尝试执行的所有操作似乎都没有效果。 我想要做的是创建一个类,该类在基类中重新定义了一些原始方法,同时仍然能够访问基类中的所有其他方法。 在上面的示例中,我希望能够做到这一点:

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

输出将是这样的:

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

我有:

  1. 源自object Base ;
  2. Base移到Derived之前;
  3. 重命名了str因为它对影子内置函数不利;
  4. 添加了代码以实例化Derived

暂无
暂无

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

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