![](/img/trans.png)
[英]Inherit attribute from class that is isn't passed into __init__ method
[英]How to inherit from a class with __init__ and take input parms
我有两个类,如下所示:
class Buttons():
def __init__(self, dDict):
self.TCT = Tool()
self.dDict = dDict
def btnName(self):
# I will use both self.TCT and self.dDict here
a = self.dDict['setup']
class Switch(Buttons):
def __init__(self):
self.TCT =Tool()
我需要实例化Switch
类,但是我需要提供dDict
以便Buttons
类可以拥有它正在寻找的数据。 实例化类Switch
的正确方法是什么?
您可以从父类继承__init__
,如下所示:
class Switch(Buttons):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Followed by init code that is used by Switch
这也意味着您不需要在新的__init__
重复self.TCT =Tool()
。
然后,您可以安全地致电
switch = Switch(mydict)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.