【发布时间】:2019-10-25 11:12:02
【问题描述】:
我正在尝试在 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' 对象没有属性 'list'
当然,self.list 应该是 False?我本质上希望 APIViewActions() 调用定义松散,例如,可以这样调用:
APIViewActions = APIViewActions(delete=True)
APIViewActions = APIViewActions(list=true, delete=True)
这将如何实现?
【问题讨论】:
-
您在
__init__行中缺少对实例的引用,即self.list = kwargs.get('list', False)
标签: python python-3.x python-3.7