从某个基类派生的所有类都必须定义一个名为“path”的属性。在鸭子打字的意义上,我可以依赖于子类中的定义:
class Base:
pass # no "path" variable here
def Sub(Base):
def __init__(self):
self.path = "something/"
另一种可能性是使用基类构造函数:
class Base:
def __init__(self, path):
self.path = path
def Sub(Base):
def __init__(self):
super().__init__("something/")
我使用的是Python 3.1。
您更喜欢什么?为什么?还有更好的方法吗?
答案 0 :(得分:11)
在Python 3.0 +中:
我会像第二个例子中那样使用参数到基类的构造函数。因为这会强制从Base派生的类提供必要的路径属性,该属性记录了类具有这样的属性并且需要派生类来提供它的事实。如果没有它,你将依赖于在类的文档字符串中的某个地方陈述(和阅读),尽管它确实有助于在文档字符串中说明特定属性的含义。
在Python 2.6 +中:
我不会使用上述任何一种;相反,我会使用:
class Base(object):
def __init__(self,path):
self.path=path;
class Sub(Base):
def __init__(self):
Base.__init__(self,"something/")
换句话说,我需要在基类的构造函数中使用这样的参数,因为它记录了所有这些类型将具有/ use /需要该特定参数并且需要提供参数的事实。但是,我不会将super()用作super is somewhat fragile and dangerous in Python,我也会通过继承object(或其他一些新式)类来使Base成为new-style class。