本文转自 https://www.cnblogs.com/cenyu/p/5713686.html

hasattr(object, name)
判断一个对象里面是否有name属性或者name方法,返回BOOL值,有name特性返回True, 否则返回False。
需要注意的是name要用括号括起来

 1 >>> class test():
2 ... name="xiaohua"
3 ... def run(self):
4 ... return "HelloWord"
5 ...
6 >>> t=test()
7 >>> hasattr(t, "name") #判断对象有name属性
8 True
9 >>> hasattr(t, "run") #判断对象有run方法
10 True
11 >>>

getattr(object, name[,default])
获取对象object的属性或者方法,如果存在打印出来,如果不存在,打印出默认值,默认值可选。
需要注意的是,如果是返回的对象的方法,返回的是方法的内存地址,如果需要运行这个方法,
可以在后面添加一对括号。

 1 >>> class test():
2 ... name="xiaohua"
3 ... def run(self):
4 ... return "HelloWord"
5 ...
6 >>> t=test()
7 >>> getattr(t, "name") #获取name属性,存在就打印出来。
8 'xiaohua'
9 >>> getattr(t, "run") #获取run方法,存在就打印出方法的内存地址。
10 <bound method test.run of <__main__.test instance at 0x0269C878>>
11 >>> getattr(t, "run")() #获取run方法,后面加括号可以将这个方法运行。
12 'HelloWord'
13 >>> getattr(t, "age") #获取一个不存在的属性。
14 Traceback (most recent call last):
15 File "<stdin>", line 1, in <module>
16 AttributeError: test instance has no attribute 'age'
17 >>> getattr(t, "age","18") #若属性不存在,返回一个默认值。
18 '18'
19 >>>

setattr(object, name, values)
给对象的属性赋值,若属性不存在,先创建再赋值。

 1 >>> class test():
2 ... name="xiaohua"
3 ... def run(self):
4 ... return "HelloWord"
5 ...
6 >>> t=test()
7 >>> hasattr(t, "age") #判断属性是否存在
8 False
9 >>> setattr(t, "age", "18") #为属相赋值,并没有返回值
10 >>> hasattr(t, "age") #属性存在了
11 True
12 >>>

一种综合的用法是:判断一个对象的属性是否存在,若不存在就添加该属性。

 1 >>> class test():
2 ... name="xiaohua"
3 ... def run(self):
4 ... return "HelloWord"
5 ...
6 >>> t=test()
7 >>> getattr(t, "age") #age属性不存在
8 Traceback (most recent call last):
9 File "<stdin>", line 1, in <module>
10 AttributeError: test instance has no attribute 'age'
11 >>> getattr(t, "age", setattr(t, "age", "18")) #age属性不存在时,设置该属性
12 '18'
13 >>> getattr(t, "age") #可检测设置成功
14 '18'
15 >>>

【Python】hasattr() getattr() setattr() 使用方法详解的更多相关文章

  1. hasattr() getattr() setattr() 函数使用详解??

    hasattr(object, name)函数: 判断一个对象里面是否有name属性或者name方法,返回bool值,有name属性(方法)返回True,否则返回False. **注意:name要使用 ...

  2. python中requests库使用方法详解

    目录 python中requests库使用方法详解 官方文档 什么是Requests 安装Requests库 基本的GET请求 带参数的GET请求 解析json 添加headers 基本POST请求 ...

  3. Python操作SQLite数据库的方法详解

    Python操作SQLite数据库的方法详解 本文实例讲述了Python操作SQLite数据库的方法.分享给大家供大家参考,具体如下: SQLite简单介绍 SQLite数据库是一款非常小巧的嵌入式开 ...

  4. Python hasattr,getattr,setattr,delattr

    #!/usr/bin/env python # -*- coding:utf-8 -*- # 作者:Presley # 邮箱:1209989516@qq.com # 时间:2018-11-04 # 反 ...

  5. Python学习笔记:魔术方法详解

    准备工作 为了确保类是新型类,应该把 _metaclass_=type 入到你的模块的最开始. class NewType(Object): mor_code_here class OldType: ...

  6. 一文秒懂!Python字符串格式化之format方法详解

    format是字符串内嵌的一个方法,用于格式化字符串.以大括号{}来标明被替换的字符串,一定程度上与%目的一致.但在某些方面更加的方便 1.基本用法 1.按照{}的顺序依次匹配括号中的值 s = &q ...

  7. python的内置模块re模块方法详解以及使用

    正则表达式 一.普通字符 .     通配符一个.只匹配一个字符 匹配任意除换行符"\n"外的字符(在DOTALL模式中也能匹配换行符 >>> import re ...

  8. python中os模块函数方法详解最全最新

    os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径 import os print(os.getcwd()) os.chdir("dirname") 改 ...

  9. 【转】Python的hasattr() getattr() setattr() 函数使用方法详解

    Python的hasattr() getattr() setattr() 函数使用方法详解 hasattr(object, name)判断一个对象里面是否有name属性或者name方法,返回BOOL值 ...

随机推荐

  1. GeoServer服务器环境的搭建

    .java 的安装  下载地址:http://www.oracle.com/technetwork/java/javase/downloads/index.html 我下载的java 1.8版本 1. ...

  2. eolinker 安装时遇到的坑

    Access denied for user 'root'@'localhost' (using password:YES) 从githup 上下载的代码,直接把release 里的文件发布到服务器上 ...

  3. ranch 源码分析(一)

    以前写了一个ranch的处理流程,http://www.cnblogs.com/tudou008/p/5197314.html ,就只有一张图,不是很清晰,现在有空做个源码分析. ranch的源码(版 ...

  4. MongoDB基本增删改查

    一. 在Node中如何操作 MongoDB数据  1.使用官方的 mongodb 来操作:https://github.com/mongodb/node-mongodb-native  2.使用第三方 ...

  5. WCF发布到IIS 7.0,并以https访问

    一.IIS 7.0中如何生成服务器证书,并要求网站以http访问可参考: http://www.cnblogs.com/chnking/archive/2008/10/07/1305811.html ...

  6. linux 使用split分割大文件

    1.分割 -- split命令 可以指定按行数分割和按字节大小分割两种模式. (1) 按行数分割 $ split -l 300 large_file.txt new_file_prefix 加上-d, ...

  7. js实现下拉框模糊查询

    keyup方法触发模糊查询 list : Array<any> //下拉列表所有内容 filtList:Array<any> //过滤后的内容 inputContent : s ...

  8. 跟随我在oracle学习php(9)

    三目运算符:表达式? 表达式: 表达式: 自增在前在后没有影响 参与表达式需要注意 在前先计算,在后最后加1. + 字符串拼接. 字符串转数字:从左到右第一个不是数字的位置结束 取整 parseInt ...

  9. C语言:统计数字空格其他字符程序

    #include <stdio.h> int main(){ char t; int num=0; int spac=0; int other=0; int sum=0; printf(& ...

  10. LeetCode 33 搜索旋转排序数组

    题目: 假设按照升序排序的数组在预先未知的某个点上进行了旋转. ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] ). 搜索一个给定的目标值,如果数组中存在这个 ...