[英]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")
我有:
object
Base
; Base
移到Derived
之前; str
因為它對影子內置函數不利; Derived
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.