[英]Adding to a class dynamically
I've created a new class and I'm trying to add to that class dynamically, I've created a list, that I want to put multiple objects in, then I will iterate over that list in Django (is this the correct way of doing things?) 我创建了一个新类,并尝试动态添加到该类中,创建了一个列表,我想在其中添加多个对象,然后在Django中遍历该列表(这是正确的方法做事?)
but I'm getting the below error 但我收到以下错误
TypeError: __init__() takes exactly 9 arguments (1 given)
I know what the error means, I'm just wonder how I go about creating a new instance of my objects and adding to it on the fly easily? 我知道错误的含义,我只是想知道如何创建对象的新实例并轻松地对其进行动态添加?
### create User Object
class User:
def __init__(self, Policy, Level, StartDate, EndDate, StartTime, EndTime, Name, Mobile):
self.Policy = Policy
self.Level = Level
self.StartDate = StartDate
self.EndDate = EndDate
self.StartTime = StartTime
self.EndTime = EndTime
self.Name = Name
self.Mobile = Mobile
def __init__(self):
pass
### Get all the Polices ###
lstOnCall = []
for objPolicy in objPolicyData['escalation_policies']:
strPolicyName = objPolicy['name']
if strPolicyName.lower().find('test') == -1:
for objOnCall in objPolicy['on_call']:
objUser = User()
objUser.Policy = strPolicyName
objUser.Level = objOnCall['level']
objUser.StartDate = getDate(objOnCall['start'])
objUser.EndDate = getDate(objOnCall['end'])
objUser.StartTime = getTime(objOnCall['start'])
objUser.EndTime = getTime(objOnCall['end'])
objUser = objOnCall['user']
objUser.Name = objUser['name']
objUser.Mobile = getUserMobile(objUser['id'])
lstOnCall.append(objUser)
print lstOnCall
UPDATE: adding the below works, i just need to know how to print the items now? 更新:添加以下作品,我只需要知道如何立即打印项目?
def __init__(self):
pass
the below 下面
for item in lstOnCall:
print item()
returns 退货
print item()
AttributeError: User instance has no __call__ method
You can write a dynamic constructor ( def __init__
) for your class so: 您可以为您的类编写动态构造函数( def __init__
),以便:
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])
__attrs
stores the variables names. 变量__attrs
存储变量名。 I used double underscore variable, so that it's inaccessible from extend. 我使用了双下划线变量,因此从扩展中无法访问它。 user = User()
print(user.__attrs)
Traceback (most recent call last):
print(user.__attrs)
AttributeError: 'User' object has no attribute '__attrs'
Yes, there are other method to access double underscore variable, but no one will do that ;) 是的,还有其他方法可以访问双下划线变量,但是没有人会这样做;)
__repr__
return the string
by calling print
or str
, if the function __str__
doesn't exist. 该功能__repr__
返回string
通过调用print
或str
,如果函数__str__
不存在。 Now test it 现在测试
>>> u1 = User(Name='user1')
>>> u2 = User(Name='user2', Policy=1, Level=3)
>>> print(u1)
Policy: None, Level: None, StartDate: None, EndDate: None, StartTime: None, EndTime: None, Name: 'user1', Mobile: None
>>> print(u2)
Policy: 1, Level: 3, StartDate: None, EndDate: None, StartTime: None, EndTime: None, Name: 'user2', Mobile: None
If you use my codes, you can print the items in your case so: 如果您使用我的代码,则可以根据情况打印项目:
for item in lstOnCall:
print item
Other problem of your code 您的代码的其他问题
There aren't the definition Function overloading
in Python. Python中没有定义Function overloading
。 You can define multiple function with the same name in python. 您可以在python中用相同的名称定义多个函数 。 But it doesn't make any sense. 但这没有任何意义。 Only the last definition remains in your class
/ module
. 只有最后一个定义保留在您的class
/ module
。 The previous definitions will be overwritten . 先前的定义将被覆盖 。 What you are doing with 你在做什么
class User:
def __init__(self, a, b, c):
...
def __init__(self):
pass
is False . 是False 。 It works in Java or C# but not in Python . 它可以在Java或C#中工作,但不能在Python中工作 。 The function def __init__(self, a, b, c)
will be overwritten. 函数def __init__(self, a, b, c)
将被覆盖。 Only the function def __init__(self)
exists in your class. 您的类中仅存在函数def __init__(self)
。
Try this, 尝试这个,
class User:
def __init__(self,*args,**kargs):
if len(kargs)==0 : ''' No param passed '''
self.Policy = 'Some'
self.Level = 0
else:
self.Policy = kargs['Policy']
self.Level = kargs['Level']
[..]
user= User()
user1= User(Policy='Some',Level=13)
您可以将__init__
所有参数默认设置为None
:
def __init__(self, Policy=None, Level=None, etc...):
Convert the positional parameters of your constructor method to named, optional parameters with a useful default value: 使用有用的默认值将构造函数方法的位置参数转换为命名的可选参数:
class User:
def __init__(self, Policy=Null, Level=1,
StartDate="2016-01-01", EndDate="2016-12-31",
StartTime="00:00", EndTime="23:59",
Name="UNKNOWN", Mobile=""):
self.Policy = Policy
self.Level = Level
self.StartDate = StartDate
self.EndDate = EndDate
self.StartTime = StartTime
self.EndTime = EndTime
self.Name = Name
self.Mobile = Mobile
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.