简体   繁体   English

在构造函数中处理继承的更好方法

[英]Better way to handle inheritance in constructors

I have the following BaseClass我有以下基类

class A(object):
    __metaclass__ = abc.ABCMeta
    def __init__(self, val1, val2):
        self.v1 = val1
        self.v2 = val2

and then some extended class:然后是一些扩展类:

class B(A):
    def __init__(self, *args, **kwargs):
        super(self.__class, self).__init(*args[:len(args)-1], **kwargs
        self.v3 = args[len(args)]

basically i want to call it in a way such that:基本上我想这样称呼它:

x = B(1, 2, 34) x = B(1, 2, 34)

but this seems that i need to have a specific order, how do implement init the right way so that the base class can initialize its v1,v2 variables and the extended class B can initialize the v3 value (in this case with 34).但这似乎我需要一个特定的顺序,如何以正确的方式实现init以便基类可以初始化其 v1、v2 变量,而扩展类 B 可以初始化 v3 值(在这种情况下为 34)。

You should be explicit about the required arguments for the super class A.__init__ .您应该明确说明超类A.__init__所需的参数。 If you provide < 2 args to B then you would get an error.如果您向B提供 < 2 个参数,则会出现错误。

class B(A):
    def __init__(self, val1, val2, *args):
        super(self.__class, self).__init__(val1, val2)
        self.v3 = args  # or args.pop() or whatever

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM