Python 在继承时避免_uinit__uu和超级样板文件
假设我有以下课程:Python 在继承时避免_uinit__uu和超级样板文件,python,python-3.x,oop,inheritance,Python,Python 3.x,Oop,Inheritance,假设我有以下课程: class Base(object): def __init__(self, **kwargs): # some constructor based on the kwargs pass class Child(Base): # the method I would like to avoid def __init__(self, **kwargs): super(Child, self).__in
class Base(object):
def __init__(self, **kwargs):
# some constructor based on the kwargs
pass
class Child(Base):
# the method I would like to avoid
def __init__(self, **kwargs):
super(Child, self).__init__(**kwargs)
有没有办法避免在子类中调用\uuu init\uu
和super
的样板文件?在这个包中,用户经常会从基类继承,但我希望避免他们每次都将\uuuu init\uuu
与super
一起使用,特别是因为模式永远不会改变。但是,它仍然需要接受关键字参数
我想这是可能的使用\uuuu new\uuuu
或元类,但必须有一个更简单的方法,在基类中使用类似@classmethod
编辑:使用python3如果在子类中不需要特定的初始化,可以省略
\uuuuu init\uuuu
:
class Base:
def __init__(self, **kwargs):
# some constructor based on the kwargs
pass
class Child(Base):
pass
否则,您应该这样使用它:
class Base(object):
def __init__(self, **kwargs):
# some constructor based on the kwargs
pass
class Child(Base):
def __init__(self, **kwargs):
super().__init__(**kwargs)
#...additional specific initialization
你使用的是python 2还是python 3?我正在使用python 3忽略子类上的
\uuuu init\uuuu
方法,除非你需要扩展初始化。哇,我不知道为什么我没有想到这一点。工作完美。