[我正在用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)
如何实现?
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)
在分配属性之前,您忘记了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)