word = "manbug"
word.center(50, "#")
word.ljust(50, "#")
word.rjust(50, "#")
# setattr
setattr(object, name, value)
设置object名称为name的属性值为value
eg:
hotel = Hotel.objects.all()[0]
ins, status = models.objects.get_or_create(xx=xx)
for k, v in hotel.__dict__.items():
setattr(ini, k, v)
#
# getattr
getattr(object, name, default):
返回object名称为name的属性值,如果属性name存在,如果属性name不存在,则触发AttributError异常或当可选参数default定义时返回default值。
#
# __dict__
class Person:
def __init__(self,_obj):
self.name = _obj['name']
self.age = _obj['age']
self.energy = _obj['energy']
self.gender = _obj['gender']
self.email = _obj['email']
self.phone = _obj['phone']
self.country = _obj['country']
利用__dict__的特性,上面的类可以用如下的代替,代码量大大减少:
class Person:
def __init__(self,_obj):
self.__dict__.update(_obj)
网友评论