0

I'm working with multiple classes that share some initial common variables/attributes. In order to make it cleaner and avoid calling the same variables multiple times I want to set them all in an initial class (e.g. classA) and then load all this attributes in a classB.

So I would define:

class classA:
   def __init__(self, varA, varB, varC, ..., varZ):
      self.varA = varA
      self.varB = varB
      self.varC = varC
      (...)
      self.varZ = varZ

And then load it in a second classB

class classB:
   def __init__(self, classA):
      self.varA = classA.varA
      self.varB = classA.varB
      self.varC = classA.varC
      (...)
      self.varZ = classA.varZ

Is there a better way to make this happen, without going over all the individual attributes?

3
  • class classB(classA)? Commented Apr 14, 2021 at 17:21
  • 1
    If classB is fully derived from classA, you could inherit B from A like Rakesh suggests. If it shares only some attributes, you could have a common base class classCommon and have both classA and classB inherit from that one Commented Apr 14, 2021 at 17:22
  • I may be wrong, but from my understanding by just inheriting I would have to input all the variables again when calling classB, instead of just calling classB(classA) in the script. Commented Apr 14, 2021 at 17:25

1 Answer 1

1

You could use argument unpacking and inheritance:

class A:
    def __init__(self, *args, **kwargs):
        for k, v in kwargs.items():
            setattr(self, k, v)


class B(A):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)


data = {'varA': 'a', 'varB': 'b', 'varC': 'c'}
a = A(**data)
b = B(**data)

print(a.varB == b.varB)

Out:

True
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.