Get * args names in python method

I'm not sure if this is possible. But suppose I have a python class with a constructor like this:

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 instantiate it:

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

      

What I mean by getting the name arg is getting the names ("user", "person", "client" and "doctor").

I really want to just get the string name of the argument. Where is the user, person, etc. - some python objects with their attributes, etc, but I only need the name of how these variables (objects) are called.

+3


source to share


2 answers


  • *args

    should be used when you don't know how many arguments will be passed to your function.
  • **kwargs

    allows you to handle named arguments that you did not define beforehand (kwargs = keywords)

So **kwargs

is a dictionary added to the parameters.



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

+4


source


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 will have access to keywords and values, no matter what type they are.

0


source







All Articles