即使检查了很多问题,我也很困惑。我有2个不同的类(2个不同的脚本)&我想继承超类的__init__
方法的参数。
script1.py
class MainClass():
def __init__(self,params):
self.one=params['ONE']
self.two=params['TWO']
self.three=params['THREE']
self.four=params['FOUR']
self.five=params['FIVE']
def a():
#---------
#somecode
#Initializing other class's object to access it's method.
s=SubClass() #HERE I WANT TO PASS 'PARAMS' (WHICH IS A DICTIONARY)
s.method1(....)
script2.py
class SubClass(SuperClass):
def __init__(self,params):
#Here I want all the parameters inside the 'param' in super class.
#(one,two,three...., etc).
#By checking some SO questions, I changed class SubClass() -->
#class Subclass(SuperClass) & below line:
MainClass.__init__(self,params) #But technically I don't have anything
#in param in subclass.
def method1():
#some code...
由于子类的param没有任何东西,它给了我一个错误:
self.one=params['ONE']
TypeError: 'int' object has no attribute '__getitem__'
我没有得到:
如何以最简单的方式访问超类的所有参数到子类?我不想将个别参数(如self.one,self.two ..)传递给子类。
如果我在SubClass
内拨打第三课 - > method1
- >通过'params'调用第3类。有可能吗?
答案 0 :(得分:0)
这是你需要的吗?
<强> script1.py 强>
class MainClass():
def __init__(self,params):
# Save params for use by a
self.params = params
self.one=params['ONE']
self.two=params['TWO']
...
self.five=params['FIVE']
def a():
s=SubClass(self.params)
s.method1(...)
<强> script2.py 强>
class SubClass(SuperClass):
def __init__(self,params):
MainClass.__init__(self,params)
def method1():
#some code...
答案 1 :(得分:0)
您可以将子类的__init__()
中的任何和所有非关键字参数传递给超类,如下所示:
class SubClass(SuperClass):
def __init__(self, *params):
MainClass.__init__(self, *params)
...
同样的想法也适用于其他方法。