在python中经常会遇到给类的__init__方法中创建属性。
当要创建的属性是任意给定的时就需要用到setattr这个函数。
class Person(object):
def __init__(slef,name,gender,birth):
slef.name = name
slef.gender = gender
slef.birth = birth
xiaoming = Person('Xiao Ming','Male','1990-1-1')
print xiaoming.name
打印出来是Xiao Ming。
那么如果在定义这个类时,没想好他有什么属性时怎么办。
可以传递个列表,将要定义的东西传递进去。
class Person(object):
def __init__(slef,*list):
for attr in list:
setattr(slef,attr,'None')
list = ['name','gender','birth','job','age']
xiaoming = Person(*list)
xiaoming.name = 'Xiao Ming'
xiaoming.age = 19
print xiaoming.name
print xiaoming.job
print xiaoming.age
Xiao Ming
None
19
Process finished with exit code 0
当然了,还可以使用字典,连初始属性也一块赋值了。
class Person(object):
def __init__(slef,**dic):
for attr,values in dic.items():
setattr(slef,attr,values)
dic = {'name':'Xiao Ming','gender':'M','birth':'1990-1-1','job':'student','age':18}
xiaoming = Person(**dic)
print xiaoming.name
print xiaoming.job
print xiaoming.age
执行结果
Xiao Ming
student
18
Process finished with exit code 0