[英]Using __init__ and inheritance in python
I'm a little confused regarding using __init__
and inheritance and would love to get some help with it. 对于使用__init__
和继承,我有些困惑,很想获得一些帮助。
I have a class [that can not be changed]: 我有一个课程[无法更改]:
class A(object):
def __init__(self, param1 = 7, param2 = 10):
self.x = param1
self.y = param2
def func1(self):
op1()
op2()
def func2(self):
pass
this is some class that was written and I'm using it when overloading its functions: 这是一些已编写的类,在重载其功能时正在使用它:
class B(A):
def func1(self)
op3()
op4()
def func2(self)
op5()
My problem starts here : I want to use Class B several times and sent each time different parameter: 我的问题从这里开始:我想多次使用B类,并每次发送不同的参数:
---new .py file: ---
def myFunction():
myInstance = B()
I want to do something like : 我想做这样的事情:
def myFunction():
myInstance = B(40,"test")
I thought adding to B class - __init__
but the problem is that now I'm not sure what self
it would use : explanation : Inside B class I have overloaded func2(self)
I thought writing : 我以为添加到B类__init__
但是问题是现在我不确定它将使用什么self
:解释:在B类内部,我想重载func2(self)
我想写:
class B(A):
def __init__(self, paramNumber, paramString)
self.paramNumber = paramNumber
self.paramString = paramString
but now in func2(self)
, what self
is used? 但是现在在func2(self)
,使用了什么self
? the new one? 新的那一个? the old one? 旧的? will it work? 能行吗 meaning I will have : self.x , self.y and self.paramNumber self.parmString ?
这意味着我将拥有: self.x , self.y and self.paramNumber self.parmString ?
they are different "selfs" 他们是不同的“自我”
Editing : Should I use super as well? 编辑:我也应该使用super吗?
class B(A):
def __init__(self, paramNumber, paramString,param1, param2)
self.paramNumber = paramNumber
self.paramString = paramString
super(B,self).__init__(param1,param2)
def myFunction():
myInstance = B(40,"test")
// I will get : self.x = 7
// self.y= 10
// self.paramNumber=40
//self.paramString = "test"
is this the correct solution? 这是正确的解决方案吗?
So basically you want to run __init__
from parent class inside child: 因此,基本上,您想从child内的父类运行__init__
:
class B(A):
def __init__(self, paramNumber, paramString):
super(B, self).__init__(param1=1, param2=2)
# the other code goes here
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.