【发布时间】:2017-09-23 02:10:15
【问题描述】:
尽管我有多年的 Python 编程经验,但每次遇到此类问题时,我都会使用内置的 isinstance 函数。但是,我不确定这是否是在 python 中做这些事情的理想方式。
所以,我有一个基类,我的大多数实例都是。
class Base():
def a(self):
return 1
我还有一个稍微不同的类,看起来像这样:
class Extended(Base):
def b(self):
return 2
现在,第三个类可能具有附加功能,具体取决于接收到的参数,该参数将是先前类之一的实例。
class User():
def __init__(self, arg):
... # do some common work
if isinstance(arg, Extended):
...
# define more functionality which will call method 'b'
# at some point during runtime (as event handler or smth)
在这个简单的例子中,这真的是使用 Python 的方式吗,或者我应该考虑将 Base 的接口更改为:
class Base2():
supports_more_func = False
def a(self):
return 1
def b(self):
pass
class Extended2(Base2):
supports_more_func = True
def b(self):
return 2
class User():
def __init__(self, arg):
... # do some common work
if arg.supports_more_func:
...
# define more functionality which will call method 'b'
# at some point during runtime (as event handler or smth)
您认为哪种方法更好,为什么?
【问题讨论】:
标签: python inheritance interface