Home > other >  How to access base class method *args from child class object?
How to access base class method *args from child class object?

Time:01-08

I am trying to get base class method *args from child class object. Here is the code:

class BaseView():

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


class SecondLevelClass(BaseView):

    def print_kwargs(self):
        for key, value in self.__dict__.items():
            print(key, value)

        for x in self.args:
            print(x)

some_object = SecondLevelClass('something', name="John", second_name="Keller", age=23, 
                               location='France')

print(vars(some_object))
print(type(some_object))
print(some_object.print_kwargs())

The error message says: AttributeError: 'SecondLevelClass' object has no attribute 'args'

How do I get the *args that were passed to __init__ if I want to print them?

UPDATE: Updated the code with missing lines.

CodePudding user response:

You can get it to work if you save a copy of the attributes in the __init__() method of the derived class, so its print_kwargs() method can access them.

Here's what I mean:

class BaseView():

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


class SecondLevelClass(BaseView):

    # ADDED
    def __init__(self, *args, **kwargs):
        self.args = args
        super().__init__(*args, **kwargs)

    def print_kwargs(self):
        for key, value in self.__dict__.items():
            print(key, value)

        for x in self.args:
            print(x)

some_object = SecondLevelClass('something', name="John", second_name="Keller", age=23,
                               location='France')

print(vars(some_object))
print(type(some_object))
print(some_object.print_kwargs())
  •  Tags:  
  • Related