用* args和** kwargs在Python中初始化类Object()的正确方法

问题描述 投票:3回答:2

[我正在用Python中的*args**kwargs进行一些小的类初始化,但是我遇到了object has no attribute named x错误。

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)

所以,当它被称为:

APIViewActions.retrieve_actions()

我收到以下错误:

AttributeError:“ APIViewActions”对象没有属性“列表”

当然,self.list应该是False吗?我本质上希望对APIViewActions()调用进行宽松定义,例如可以这样调用:

APIViewActions = APIViewActions(delete=True)

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

如何实现?

python python-3.x python-3.7
2个回答
3
投票

self在课程中丢失。

class APIViewActions():
    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)

2
投票

在分配属性之前,您忘记了self(使用名称作为惯例)来引用您的实例。

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)
© www.soinside.com 2019 - 2024. All rights reserved.