将参数传递给基类构造函数或使用实例变量?

dea*_*mon 8 python oop parameters constructor python-3.x

从某个基类派生的所有类都必须定义一个名为"path"的属性.在鸭子打字的意义上,我可以依赖于子类中的定义:

class Base:
    pass # no "path" variable here

def Sub(Base):
    def __init__(self):
        self.path = "something/"
Run Code Online (Sandbox Code Playgroud)

另一种可能性是使用基类构造函数:

class Base:
    def __init__(self, path):
        self.path = path

def Sub(Base):
    def __init__(self):
        super().__init__("something/")
Run Code Online (Sandbox Code Playgroud)

我使用Python 3.1.

你更喜欢什么?为什么?有没有更好的办法?

Mic*_*yan 12

在Python 3.0+中:
我会在第二个示例中使用参数到基类的构造函数.由于这迫使从基地派生的类提供必要的路径属性,它记录了班里有这样的属性和派生类必须提供它的事实.如果没有它,你将依赖于在类的文档字符串中的某个地方陈述(和阅读),尽管它确实有助于在文档字符串中说明特定属性的含义.

在Python 2.6+中:
我不会使用上述任何一种; 相反,我会使用:

class Base(object):
    def __init__(self,path):
        self.path=path;

class Sub(Base):
    def __init__(self):
       Base.__init__(self,"something/")
Run Code Online (Sandbox Code Playgroud)

换句话说,我需要在基类的构造函数中使用这样的参数,因为它记录了所有这些类型将具有/ use /需要该特定参数并且需要提供参数的事实.但是,我不会使用super(),因为super在Python中有点脆弱和危险,我也会通过继承object(或其他一些新式)类使Base成为一个新式的类.

  • `super()`没什么脆弱的.脆弱性在2.x语法中,它在3.x(OP正在使用,如`super()`调用所示)中固定,并且通常是多重继承.没有理由在Python 3.x中直接调用baseclass方法,`super().__ init(...)`语法永远不会更糟,通常更好. (5认同)