【发布时间】:2016-01-06 07:40:10
【问题描述】:
我刚刚开始从视频课程中学习 python,在本课程中作为多态性示例提供了以下代码:
class network:
def cable(self): print('I am the cable')
def router(self): print('I am the router')
def switch(self): print('I am the switch')
class tokenRing(network):
def cable(self): print('I am a token ring network cable')
def router(self): print('I am a token ring router')
class ethernet(network):
def cable(self): print('I am an ethernet network cable')
def router(self): print('I am an ethernet router')
def main():
windows=tokenRing()
mac=ethernet()
windows.cable()
mac.cable()
main()
现在,我真的不认为这是一个好的多态示例。我不确定那是多态性!事实上,如果我删除 network 类(当然还有继承),代码的工作方式完全相同。所以我在想,如果你不使用基类,那就不是真正的多态。
我是对还是错?有人可以修改这个例子,让它真正呈现多态性的要点(即实际上利用了基类)吗?
【问题讨论】:
-
这不是 Python 的好例子(推荐阅读:python.org/dev/peps/pep-0008),更不用说多态了。为什么不使用现有示例(例如stackoverflow.com/q/3724110/3001761)?
标签: python inheritance polymorphism