调用父类的构造函数中使用不同的参数蟒蛇 [英] Calling superclass constructors in python with different arguments

查看:145
本文介绍了调用父类的构造函数中使用不同的参数蟒蛇的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class A():
    def __init__( self, x, y):
        self.x = x
        self.y = y

class B():
    def __init__( self, z=0):
        self.z = z  

class AB(A,B):
    def __init__( self, x, y, z=0):
        ?

我怎样才能让AB的构造函数中调用A和B的构造函数使用适当的参数?

How can I make the constructor of AB call the constructors for A and B with the proper arguments?

我试过

class AB(A,B):
    def __init__( self, x, y, z=0):
        A.__init__(x,y)
        B.__init__(z)

但是这给了我一个错误。

but this gives me an error.

推荐答案

您没有通过

class AB(A, B):
    def __init__(self, x, y, z=0):
        A.__init__(self, x, y)
        B.__init__(self, z)

请注意,如果这个继承层次变得更为复杂,你会碰到与构造函数不执行或重新执行得到的问题。考虑 超级 (和问题超级 )和唐别忘了继承对象如果您对2.x和你的类不从别的继承。

Note that if this inheritance hierarchy gets more complicated, you'll run into problems with constructors not executing or getting reexecuted. Look into super (and the problems with super), and don't forget to inherit from object if you're on 2.x and your class doesn't inherit from anything else.

这篇关于调用父类的构造函数中使用不同的参数蟒蛇的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆