所有派生自某个基类的类都必须定义一个名为“路径”的属性。在鸭子类型的意义上,我可以依赖子类中的定义:
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。
您更喜欢什么,为什么?有没有更好的办法?
最佳答案
在 Python 3.0+ 中:
我会像第二个示例中那样为基类的构造函数提供一个参数。由于这会强制从 Base 派生的类提供必要的路径属性,这记录了该类具有此类属性并且派生类需要提供它的事实。没有它,您将依赖于在您类(class)的文档字符串中的某处陈述(和阅读),尽管在文档字符串中也说明特定属性的含义确实有帮助。
在 Python 2.6+ 中:
我不会使用以上任何一种;相反,我会使用:
class Base(object):
def __init__(self,path):
self.path=path;
class Sub(Base):
def __init__(self):
Base.__init__(self,"something/")
换句话说,我会在基类的构造函数中需要这样一个参数,因为它记录了这样一个事实,即所有此类类型都将拥有/使用/需要该特定参数,并且需要提供该参数。但是,我不会将 super() 用作 super is somewhat fragile and dangerous in Python , 我也会让 Base 成为 new-style class通过从对象(或其他一些新样式)类继承。
关于python - 将参数传递给基类构造函数或使用实例变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2728346/