Search code examples
pythonpython-3.xpython-3.7

Correct way to initialise a class Object() in Python with *args and **kwargs


I'm trying my hand at a little class initialisation, with *args and **kwargs, in Python, and I am coming up with a object has no attribute named x error.

class APIViewActions():
    def __init__(self, *args, **kwargs):
        list = kwargs.get('list', False)
        create = kwargs.get('create', False)
        retrieve = kwargs.get('retrieve', False)
        update = kwargs.get('update', False)
        partial_update = kwargs.get('partial_update', False)
        destroy = kwargs.get('destroy', False)

    def retrieve_actions(self):
        actions = {}

        if self.list:
            actions['get'] = 'list'

        if self.create:
            actions['post'] = 'create'

        if self.retrieve:
            actions['get'] = 'retrieve'

        if self.update:
            actions['patch'] = 'update'

        if self.partial_update:
            actions['patch'] = 'partial_update'

        if self.destroy:
            actions['delete'] = 'destroy'

        return actions

APIViewActions = APIViewActions(delete=True)

So, when this is called:

APIViewActions.retrieve_actions()

I receive the following error:

AttributeError: 'APIViewActions' object has no attribute 'list'

Surely, self.list should be False? I essentially want the APIViewActions() call to be loosely defined, e.g., could be called like this:

APIViewActions = APIViewActions(delete=True)

APIViewActions = APIViewActions(list=true, delete=True)

How would this be achieved?


Solution

  • You forget the self (name use as a convention) to refer your instance before assigning attributes.

    def __init__(self, *args, **kwargs): 
        self.list = kwargs.get('list', False) 
        self.create = kwargs.get('create', False) 
        self.retrieve = kwargs.get('retrieve', False) 
        self.update = kwargs.get('update', False) 
        self.partial_update = kwargs.get('partial_update', False) 
        self.destroy = kwargs.get('destroy', False)