python的构造函数参数不一样,如何使用许多参数覆盖Python类的构造函数?

本文探讨了在Python中如何在子类中优雅地重载父类的构造函数,特别是在不知道父类构造函数参数的情况下。通过使用`*args`和`**kwargs`,可以传递任意数量的位置参数和关键字参数给父类的构造函数,实现子类构造函数的扩展。示例代码展示了如何在`Foo`类中添加新的参数,同时调用`Bar`类的构造函数。
摘要由CSDN通过智能技术生成

Say, I have a class Foo, extending class Bar. And I want to slightly override Foo's consructor. And I don't want even know what signarure of Bar's constructors is. Is there a way to do this?

If you didn't understand, I mean the following:

class Bar:

def __init__ (self, arg1=None, arg2=None, ... argN=None):

....

class Foo (Bar):

#Here i just want add additional parameter to constructor, but don't want to know anything about Bar's other parameters (arg1, arg2..., argN)

def __init__ (self, my_new_arg=None, ??? )

self.new_arg = my_new_arg

Bar.__init__(self, ??? )

Is there a way to put something short and elegant instead of ??? in this code?

(Maybe some variations of args/kwargs)

解决方案

class Parent(object):

def __init__(self, a, b):

print 'a', a

print 'b', b

class Child(Parent):

def __init__(self, c, d, *args, **kwargs):

print 'c', c

print 'd', d

super(Child, self).__init__(*args, **kwargs)

test = Child(1,2,3,4)

Output:

c 1

d 2

a 3

b 4

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值