irahorecka
irahorecka

Reputation: 1807

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

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)

Upvotes: 0

Views: 284

Answers (1)

rchome
rchome

Reputation: 2723

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')

Upvotes: 1

Related Questions