setattr给实例对象动态添加实例属性

个人总结:使用setattr在实例对象初始化的时候添加属性,添加的属性值对该实例有效!

help 帮助

setattr(obj,key,value)  # 添加属性 
Help on built-in function setattr in module builtins:
setattr(obj, name, value, /)
    Sets the named attribute on the given object to the specified value.
    
    setattr(x, 'y', v) is equivalent to ``x.y = v''

getattr(obj,key[,default)# 获取属性
Help on built-in function getattr in module builtins:
getattr(...)
    getattr(object, name[, default]) -> value
    
    Get a named attribute from an object; getattr(x, 'y') is equivalent 
    to x.y.When a default argument is given, it is returned when the 
    attribute doesn'texist; without it, an exception is raised in that case.

Demo

class Demo():
    ...:     def __init__(self,**kwargs):
    ...:         if len(kwargs):
    ...:             for key,value in kwargs.items():
    ...:                 setattr(self,key,value)
    ...:     def get(self,key):
    ...:         print(getattr(self,key))

运行

d1 = Demo()
In [41]: d2 = Demo(name="uu",age=19,gender="man")

In [42]: d2.get("age")
19

In [4]: d2.age
Out[4]: 19

In [5]: d2.name
Out[5]: 'uu'

In [6]: d1.name
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-6-b4b047799657> in <module>()
----> 1 d1.name

AttributeError: 'Demo' object has no attribute 'name'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值