我试图创建一个我的类对象的空实例并将其添加到列表中,但是,一旦我尝试创建对象添加新数据,我就会收到错误,如下所示:
错误
Traceback (most recent call last):
File "pagerduty.py", line 96, in <module>
UserData = User()
TypeError: 'dict' object is not callable
码
class User(object):
__attrs = ['Policy','Level', 'StartDate', 'EndDate', 'StartTime',
'EndTime', 'Name', 'Mobile']
def __init__(self, **kwargs):
for attr in self.__attrs:
setattr(self, attr, kwargs.get(attr, None))
def __repr__(self):
return ', '.join(
['%s: %r' % (attr, getattr(self, attr)) for attr in self.__attrs])
OnCallData = []
for User in objPolicyData['users']:
UserData = User()
UserData.Name = User['name']
UserData.Mobile = UserMobile = getUserMobile(User['id'])
for OnCall in User['on_call']:
UserPolicy = OnCall['escalation_policy']
PolicyName = UserPolicy['name']
if PolicyName.lower().find('test') == -1:
UserData.Policy = PolicyName
UserData.Level = OnCall['level']
UserData.StartDate = getDate(OnCall['start'])
UserData.EndDate = getDate(OnCall['end'])
UserData.StartTime = getTime(OnCall['start'])
UserData.EndTime = getTime(OnCall['end'])
OnCallData.append(UserData)
答案 0 :(得分:2)
在for
范围内,User
标识符是来自objPolicyData['users']
的迭代值(正如您在UserData.Name = User['name']
中使用的那样)
您需要为迭代使用不同的名称 类似的东西:
for userI in objPolicyData['users']:
UserData = User()
UserData.Name = userI['name']
UserData.Mobile = UserMobile = getUserMobile(userI['id'])
for OnCall in userI['on_call']:
UserPolicy = OnCall['escalation_policy']
PolicyName = UserPolicy['name']
if PolicyName.lower().find('test') == -1:
UserData.Policy = PolicyName
UserData.Level = OnCall['level']
UserData.StartDate = getDate(OnCall['start'])
UserData.EndDate = getDate(OnCall['end'])
UserData.StartTime = getTime(OnCall['start'])
UserData.EndTime = getTime(OnCall['end'])
请注意,使用这些约定可以防止此错误。意思是,以小写字母(user
)开头的变量名称和大写字母(User
)的类。
这与大多数变量名称相关
答案 1 :(得分:2)
您的类和正在迭代的变量都称为holder
。将其中一个更改为其他名称。
按照惯例,python变量名是小写的。所以我建议做出以下改变:
User
等等。这遵循pep8中的命名约定。这也将处理您的错误。
当然,如果已经建立了样式指南,您应该遵循它并决定使用不同的for user in objPolicyData['users']:
user_data = User()
user_data.name = User['name']
user_data.mobile = UserMobile = getUserMobile(User['id'])
for on_call in User['on_call']:
user_policy = on_call['escalation_policy']
policy_name = user_policy['name']
if policy_name.lower().find('test') == -1:
user_data.policy = policy_name
user_data.level = on_call['level']
user_data.start_date = get_date(on_call['start'])
名称(迭代变量)。