(转)详解Python3 中hasattr()、getattr()、setattr()、delattr()函数及示例代码数
原文:https://www.jb51.net/article/138363.htm
hasattr()函数
hasattr()函数用于判断是否包含对应的属性
语法:
hasattr(object,name)
参数:
object--对象
name--字符串,属性名
返回值:
如果对象有该属性返回True,否则返回False
示例:
class People:
country='China'
def __init__(self,name):
self.name=name
def people_info(self):
print('%s is xxx' %(self.name))
obj=People('aaa')
print(hasattr(People,'country'))
#返回值:True
print('country' in People.__dict__)
#返回值:True
print(hasattr(obj,'people_info'))
#返回值:True
print(People.__dict__)
##{'__module__': '__main__', 'country': 'China', '__init__': <function People.__init__ at 0x1006d5620>, 'people_info': <function People.people_info at 0x10205d1e0>, '__dict__': <attribute '__dict__' of 'People' objects>, '__weakref__': <attribute '__weakref__' of 'People' objects>, '__doc__': None}
getattr()函数
描述:
getattr()函数用于返回一个对象属性值
语法:
getattr(object,name,default)
参数:
object--对象
name--字符串,对象属性
default--默认返回值,如果不提供该参数,在没有对于属性时,将触发AttributeError。
返回值:
返回对象属性值
class People:
country='China'
def __init__(self,name):
self.name=name def people_info(self):
print('%s is xxx' %(self.name))
obj=getattr(People,'country')
print(obj)
#返回值China
#obj=getattr(People,'countryaaaaaa')
#print(obj)
#报错
# File "/getattr()函数.py", line 32, in <module>
# obj=getattr(People,'countryaaaaaa')
# AttributeError: type object 'People' has no attribute 'countryaaaaaa'
obj=getattr(People,'countryaaaaaa',None)
print(obj)
#返回值None
setattr()函数
描述:
setattr函数,用于设置属性值,该属性必须存在
语法:
setattr(object,name,value)
参数:
object--对象
name--字符串,对象属性
value--属性值
返回值:
无
class People:
country='China'
def __init__(self,name):
self.name=name
def people_info(self):
print('%s is xxx' %(self.name))
obj=People('aaa')
setattr(People,'x',111) #等同于People.x=111
print(People.x)
#obj.age=18
setattr(obj,'age',18)
print(obj.__dict__)
#{'name': 'aaa', 'age': 18}
print(People.__dict__)
#{'__module__': '__main__', 'country': 'China', '__init__': <function People.__init__ at 0x1007d5620>, 'people_info': <function People.people_info at 0x10215d1e0>, '__dict__': <attribute '__dict__' of 'People' objects>, '__weakref__': <attribute '__weakref__' of 'People' objects>, '__doc__': None, 'x': 111}
delattr()函数
描述:
delattr函数用于删除属性
delattr(x,'foobar)相当于del x.foobar
语法:
setattr(object,name)
参数:
object--对象
name--必须是对象的属性
返回值:
无
示例:
class People:
country='China'
def __init__(self,name):
self.name=name
def people_info(self):
print('%s is xxx' %(self.name))
delattr(People,'country') #等同于del People.country
print(People.__dict__)
{'__module__': '__main__', '__init__': <function People.__init__ at 0x1006d5620>, 'people_info': <function People.people_info at 0x10073d1e0>, '__dict__': <attribute '__dict__' of 'People' objects>, '__weakref__': <attribute '__weakref__' of 'People' objects>, '__doc__': None}
补充示例:
class Foo:
def run(self):
while True:
cmd=input('cmd>>: ').strip()
if hasattr(self,cmd):
func=getattr(self,cmd)
func()
def download(self):
print('download....')
def upload(self):
print('upload...')
# obj=Foo()
# obj.run()
总结
以上所述是小编给大家介绍的详解Python3 中hasattr()、getattr()、setattr()、delattr()函数,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!
(转)详解Python3 中hasattr()、getattr()、setattr()、delattr()函数及示例代码数的更多相关文章
- python 内置函数的补充 isinstance,issubclass, hasattr ,getattr, setattr, delattr,str,del 用法,以及元类
isinstance 是 python中的内置函数 , isinstance()用来判断一个函数是不是一个类型 issubclass 是python 中的内置函数, 用来一个类A是不是另外一个 ...
- isinstance/type/issubclass的用法,反射(hasattr,getattr,setattr,delattr)
6.23 自我总结 面向对象的高阶 1.isinstance/type/issubclass 1.type 显示对象的类,但是不会显示他的父类 2.isinstance 会显示的对象的类,也会去找对象 ...
- 详解C++中的多态和虚函数
一.将子类赋值给父类 在C++中经常会出现数据类型的转换,比如 int-float等,这种转换的前提是编译器知道如何对数据进行取舍.类其实也是一种数据类型,也可以发生数据转换,但是这种转换只有在 子类 ...
- Python hasattr,getattr,setattr,delattr
#!/usr/bin/env python # -*- coding:utf-8 -*- # 作者:Presley # 邮箱:1209989516@qq.com # 时间:2018-11-04 # 反 ...
- 反射hasattr; getattr; setattr; delattr
hasattr(obj,name_str):#判断一个对象obj里面是否有对应的name_str字符串的方法,返回True或者Falsegetattr(obj,name_str):#根据字符串去获取对 ...
- python中hasattr, getattr,setattr及delattr四个方法
通过一个实例来说明,这四个函数的用法: 首先一个如下的一个简单的类: class Animal(object): def __init__(self,name, zone): self.name = ...
- python动态函数hasattr,getattr,setattr,delattr
hasattr(object,name) hasattr用来判断对象中是否有name属性或者name方法,如果有,染回true,否则返回false class attr(): def fun( ...
- python反射hasattr getattr setattr delattr
反射 : 是用字符串类型的名字 去操作 变量 相比于用eval('print(name)') 留有 安全隐患 反射 就没有安全问题 hasattr 语法: hasattr(object, name)o ...
- hasattr getattr setattr delattr --> (反射)
class Room: def __init__(self,name): self.name = name def big_room(self): print('bigroot') R = Room( ...
随机推荐
- 引用限定符(c++11)
1.概念 1)下面这种情况将对一个右值调用成员函数.对右值赋值 string s1 = "abc", s2 = "def"; auto n = (s1 + s2 ...
- 第03章:MongoDB启动参数说明
①基本配置 --quiet # 安静输出 --port arg # 指定服务端口号,默认端口27017 --bind_ip arg # 绑定服务IP,若绑定127.0.0.1,则只能本机访问,不指定默 ...
- 后台开发 - DPDK引发的图谱
关系图谱(点击看完整大图): 部分名词: 名词 全写 解释 备注 DPDK Data Plane Development Kit 数据平面开发套件或叫数据平面开发工具集 Intel开源的快速数据包处理 ...
- Web模板引擎—Mustache
Web模板引擎——Mustache 2012年9月12日 BY BELL·12 COMMENTS Web 模板引擎是为了使用户界面与业务数据(内容)分离而产生的,它可以生成特定格式的文档,通常是标准的 ...
- (转)私有代码存放仓库 BitBucket介绍及入门操作
转自:http://blog.csdn.net/lhb_0531/article/details/8602139 私有代码存放仓库 BitBucket介绍及入门操作 分类: 研发管理2013-02-2 ...
- MapGIS计算瓦片数据集
https://www.docin.com/p-2103834433.html
- Android webview 开启地理位置定位
WebSettings webSettings = webView.getSettings(); webSettings.setDatabaseEnabled(true); String dir = ...
- js-实现搜狐列表
<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>& ...
- appcompat_v7报错
appcompat_v7如果报找不到资源,value-xx出错.一般就是因为appcompat_v7的版本问题,直接修改api版本至appcompat_v7对应value的最高版本. 我的v7包最高对 ...
- sqoop快速入门
转自http://www.aboutyun.com/thread-22549-1-1.html