Home > Net >  How to access *args variable name(s) in __init__
How to access *args variable name(s) in __init__

Time:11-29

How do I access *args variable name(s) in __init__ method?

E.g.

class Parent:
    def __init__(self, *args):
        # How to access *args variable names here?
        # In this example: foo, bar
        pass

class Child(Parent):
    def __init__(self, foo, bar):
        super().__init__(foo, bar)

CodePudding user response:

Inspired by OP's comment, maybe you could do something like

class Parent:
    def __init__(self, *args):
        self.child_varnames = type(self).__init__.__code__.co_varnames[1:]

class Child(Parent):
    def __init__(self, foo, bar):
        super().__init__(foo, bar)

In my tests, I get

>>> c = Child(1, 2)
>>> c.child_varnames
('foo', 'bar')
  • Related