一、动态操作属性
1、hasattr(obj, name):检查obj对象是否包含名为name的属性或方法;
2、getattr(object, name[, default]):获取object对象中名为name的属性的属性值;
3、setattr(obj, name, value, /):将obj 对象的name 属性设为value。
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def info(self):
return '矩形的面积计算'
c = Rectangle(3, 5)
print(hasattr(c, 'width')) #True
print(hasattr(c, 'info')) #True
print(getattr(c, 'width')) #3
print(getattr(c, 'size', 15)) #15
setattr(c, 'width', 12)
print(getattr(c, 'width')) #12
二、属性__call__
hasattr()函数只能判断属性或方法是否存在,无法判断是属性还是方法,
可以根据属性或方法是否含有__call__属性来确定。
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def info(self):
return '矩形的面积计算'
c = Rectangle(3, 5)
print(hasattr(c.width, '__call__')) #False
print(hasattr(c.info, '__call__')) #True
def foo():
print(1111)
foo()
foo.__call__()#与foo()相同