1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| """ 动态判断是否包含属性或者设置值 hasattr(obj,name) 是否有name属性或方法 getattr(obj,name) 获取name属性值 setattr(obj,name,value,..) 设置name属性为value 属性不存在时会添加属性 可设置方法 可把方法改变成属性 """
class Comment: def __init__(self, detail, views): self.detail = detail self.views = views
def info(self): print("comment info:%s" % self.detail)
c = Comment("这个真好啊!", 66) print("hasattr('detail'):", hasattr(c, 'detail')) print("hasattr('info'):", hasattr(c, 'info')) print("hasattr('hello'):", hasattr(c, 'hello')) print("detail:", getattr(c, 'detail')) print("views:", getattr(c, 'views')) setattr(c, 'detail', '今天天气不错') print(c.detail)
def bar(): print("this is method bar")
c.info() setattr(c, 'info', bar) c.info() setattr(c, 'info', 'info message') print(c.info) ''' 通过__call__属性判断是否可调用 方法的执行就是调用.__call__()方法 可以在类中定义是的类的实例能够执行 '''
class User: def __init__(self, name): self.name = name
def info(self): print("use name is :", self.name)
def __call__(self, *args, **kwargs): print("user __call__ method")
u = User('lily') print("hasattr(u.name, '__call__'):", hasattr(u.name, '__call__')) print("hasattr(u.info, '__call__'):", hasattr(u.info, '__call__')) u()
''' 函数调用__call__() ''' bar() bar.__call__()
|