3

I am not sure if it is possible. But suppose I have some python class with constructor as follows:

class SomeClass(object):

    def __init__(self, *args):
        pass
        # here I want to iterate over args
        # get name of each arg

Suppose I use this class somewhere and create an instance of it:

some_var = SomeClass(user, person, client, doctor)

What I mean by get name of arg, is to get names ('user', 'person', 'client' and 'doctor')

I really mean just get string name of a argument. Where user, person etc. are some python objects with their attributes etc, but I only need the name of how these variables (objects) are named.

yerassyl
  • 2,958
  • 6
  • 42
  • 68

2 Answers2

4
  • *args should be used when you are unsure how many arguments will be passed to your function
  • **kwargs lets you to handle named arguments that you have not defined in advance (kwargs = keyword arguments)

So **kwargs is a dictionary added to the parameters.

https://docs.python.org/3/tutorial/controlflow.html#arbitrary-argument-lists

Jurosh
  • 6,984
  • 7
  • 40
  • 51
Drahoš Maďar
  • 517
  • 2
  • 6
  • 22
0

Use **kwargs and setattr like this:

class SomeClass(object):
    def __init__(self, **kwargs):
        for key, value in kwargs.items():
            setattr(self, key, value)

and you'll get access to the keywords and the values as well, no matter which type they are.

Franz
  • 623
  • 8
  • 14