Home > other >  How to put stuff into __init__(self): by giving parameter in variable?
How to put stuff into __init__(self): by giving parameter in variable?

Time:09-17

So, I am basically trying to write a code where i want to declare parameters during declaration some thing like:

class emp:
     def __init__(self,a,b):
          self.first_name=a
          self.last_name=b
Rohan=emp("Rohan","foo",age=12,nationality="Indian")
print(Rohan.age)

The following code yields the output:

TypeError: __ init __() got an unexpected keyword argument 'age'

What i want is:12

If possible can i aslo put default values where the following code yields

Jhonny=emp(age=,nationality='')

jhony.age=5
jhony.nationality="Indian"

CodePudding user response:

If you're sure that you want to do it this way, you can do the following:

class emp:
    def __init__(self, a, b, **kwargs):
        self.first_name = a
        self.last_name = b
        for key, val in kwargs.items():
            setattr(self, key, val)

That said, it's not great practice to do so. I would agree that it would be better to put them as optional arguments in your __init__ function.

  • Related