hasattr(obj, name)
其中 obj 指的是某个类的实例对象,name 表示指定的属性名或方法名。同时,该函数会将判断的结果(True 或者 False)作为返回值反馈回来。class CLanguage: def __init__ (self): self.name = "C语言中文网" self.add = "http://task.lmcjl.com" def say(self): print("我正在学Python") clangs = CLanguage() print(hasattr(clangs,"name")) print(hasattr(clangs,"add")) print(hasattr(clangs,"say"))
程序输出结果为:
True
True
True
getattr(obj, name[, default])
其中,obj 表示指定的类实例对象,name 表示指定的属性名,而 default 是可选参数,用于设定该函数的默认返回值,即当函数查找失败时,如果不指定 default 参数,则程序将直接报 AttributeError 错误,反之该函数将返回 default 指定的值。class CLanguage: def __init__ (self): self.name = "C语言中文网" self.add = "http://task.lmcjl.com" def say(self): print("我正在学Python") clangs = CLanguage() print(getattr(clangs,"name")) print(getattr(clangs,"add")) print(getattr(clangs,"say")) print(getattr(clangs,"display",'nodisplay'))程序执行结果为:
C语言中文网
http://task.lmcjl.com
<bound method CLanguage.say of <__main__.CLanguage object at 0x000001FC2F2E3198>>
nodisplay
setattr(obj, name, value)
首先,下面例子演示如何通过该函数修改某个类实例对象的属性值:class CLanguage: def __init__ (self): self.name = "C语言中文网" self.add = "http://task.lmcjl.com" def say(self): print("我正在学Python") clangs = CLanguage() print(clangs.name) print(clangs.add) setattr(clangs,"name","Python教程") setattr(clangs,"add","http://task.lmcjl.com/python") print(clangs.name) print(clangs.add)程序运行结果为:
C语言中文网
http://task.lmcjl.com
Python教程
http://task.lmcjl.com/python
def say(self): print("我正在学Python") class CLanguage: def __init__ (self): self.name = "C语言中文网" self.add = "http://task.lmcjl.com" clangs = CLanguage() print(clangs.name) print(clangs.add) setattr(clangs,"name",say) clangs.name(clangs)程序运行结果为:
C语言中文网
http://task.lmcjl.com
我正在学Python
def say(self): print("我正在学Python") class CLanguage: pass clangs = CLanguage() setattr(clangs,"name","C语言中文网") setattr(clangs,"say",say) print(clangs.name) clangs.say(clangs)程序执行结果为:
C语言中文网
我正在学Python
本文链接:http://task.lmcjl.com/news/7327.html