0

I have two classes as follows:

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()

I need to instantiate Switch class, but I need to provide dDict so that Buttons class will have the data it is looking for. What is the right way to instantiate the class Switch?

usustarr
  • 418
  • 1
  • 5
  • 21

1 Answers1

2

You can inherit the __init__ from your parent class as follows:

class Switch(Buttons):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # Followed by init code that is used by Switch

This also means that you don't need to repeat the self.TCT =Tool() in your new __init__.

You can then safely call

switch = Switch(mydict)
Daniel Lenz
  • 3,334
  • 17
  • 36
  • 1
    Given this is Python 3, you'd omit the arguments to `super()`, making it just `super().__init__(*args)` (and you might want to receive and pass along `**kwargs` to allow passing arguments by keyword too). – ShadowRanger May 14 '18 at 22:18
  • What would be the case if my Switch class took input parm with a default value? How do I change your code for that? – usustarr Jun 06 '18 at 12:33
  • I'd recommend to ask a new question for that, makes it easier to handle! – Daniel Lenz Jun 06 '18 at 12:42
  • I just posted it here.https://stackoverflow.com/questions/50721803/how-to-inherit-from-a-class-with-init-and-take-multiple-input-parms-with-def – usustarr Jun 06 '18 at 13:35