1

I have a parent class and several subclasses. Every subclass accepts different parameters, but all subclasses have some common parameters. I don't want to write the "common parameters" for every subclass. How can I do this?

class Parent:
    def __init__(self, name):
        self.name = name


class Subclass(Parent):
    def __init__(self, age):
         self.age = age

    def do_something(self):
         print(self.name)


instance = Subclass(name="Test", age=42)
instance.do_something()  # 42
1
  • 1
    Keep all the common attributes in the parent, so the children can inherit them (this is the whole point of inheritance). Remember that to call the parents __init__ you have to do super().__init__(name). If you're using multiple inheritance, it gets more complicated, and you should look into the Python MRO first. Commented Apr 29, 2018 at 14:40

2 Answers 2

2

You can try this:

class Subclass(Parent):
    def __init__(self, **kwargs):
         super().__init__(kwargs['name'])
         self.age = kwargs['age']

    def do_something(self):
         print(self.name)

And then use this just like you did in the question:

instance = Subclass(name="Test", age=42)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answer. The solution works. But the problem is, that there are no more parameter recommendations (for example IntelliSense) with parameters only defined in the parent class (e. g. name). Is there a way to fix that, without putting all the parameters in every single init function of the subclasses, because there are about 30 parameters and I don't want to put them in every single subclass.
0

I use it in the following manner

You can add as many child classes as you want

class ParentClass(object):
    def __init__(self,baseArgs):
        self.var1=baseArgs['var1']
        self.var2=baseArgs['var2']
        self.var3=baseArgs['var3']


class ChildClass(ParentClass):
    def __init__(self,childArgs,baseArgs):
        super(ChildClass, self).__init__(baseArgs)
        self.cvar1=childArgs['cvar1']
        self.cvar2=childArgs['cvar2']

a=ChildClass({'cvar1':40,'cvar2':50},{'var1':10,'var2':20,'var3':30})
print(a.var1)
# 10

1 Comment

Thank you for your answer. Unfortunately, this doesn't work for me, because, then I have no more parameter recommendation.

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.