Python对象的属性可以通过obj.__dict__获得,向其中添加删除元素就可以实现python对象属性的动态添加删除的效果,不过我们应该使用更加正规的getattr和setattr来进行这类操作

 

])

Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.

getattr可以动态的获取对象的属性,default可以指定如果名为name的属性不存在时返回的值,如果不指定而object中又没有该属性名称,则返回AttributeError

 1 >>> class Demo(object):
 2 ...     def __init__(self):
 3 ...             self.name = 'Demo'
 4 ...     def count(self):
 5 ...             return len(self.name)
 6 ...
 7 >>> X = Demo()
 8 >>> X.count()
 9 4
10 >>> getattr(X, 'count')()
11 4
12 >>> getattr(X, 'name')
13 'Demo'
14 >>> getattr(X, 'notexist')
15 Traceback (most recent call last):
16   File "<stdin>", line 1, in <module>
17 AttributeError: 'Demo' object has no attribute 'notexist'
18 >>> getattr(X, 'notexist', 'default_value')
19 'default_value'
setattr(object, name, value)

This is the counterpart of getattr(). The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example, setattr(x, 'foobar', 123) is equivalent to x.foobar = 123.

 与getattr对应,setattr用来动态的设定一个对象的属性,用来构造配置类对象内非常合适

>>> Y = Demo()
>>> setattr(Y, 'color', 'red')
>>> Y.color
'red'
View Code

相关文章: