python eval() hasattr() getattr() setattr() 函数使用方法详解
eval() 函数 --- 将字符串str当成有效的表达式来求值并返回计算结果。
语法:eval(source[, globals[, locals]]) ---> value
参数:
source:一个Python表达式或函数compile()返回的代码对象
globals:可选。必须是dictionary
locals:可选。任意map对象
实例1:
可以把list,tuple,dict和string相互转化。
a = '[[1,2], [3,4], [5,6], [7,8]]'
a = '[{'name':'haha','age':18}]'
print(type(a), a) #<class 'str'> b = eval(a)
print(type(b), b) #<class 'list'> c = '{"name":"aaa", "age":18}'
print(type(c), c) #<class 'str'>
d = eval(c)
print(type(d), d) #<class 'dict'> e = "([1,2], [3,4], [5,6], [7,8], (9,0))"
print(type(e), e)
f = eval(e)
print(type(f), f) #<class 'tuple'>
运行结果:
<class 'str'> [[1,2], [3,4], [5,6], [7,8]]
<class 'list'> [[1, 2], [3, 4], [5, 6], [7, 8]]
<class 'str'> {"name":"aaa", "age":18}
<class 'dict'> {'name': 'aaa', 'age': 18}
<class 'str'> ([1,2], [3,4], [5,6], [7,8], (9,0))
<class 'tuple'> ([1, 2], [3, 4], [5, 6], [7, 8], (9, 0))
实例2:
在编译语言里要动态地产生代码,基本上是不可能的,但动态语言是可以,意味着软件已经部署到服务器上了,但只要作很少的更改,只好直接修改这部分的代码,就可立即实现变化,不用整个软件重新加
a=1
g={'a':20}
eval("a+1",g)
运行结果:21
hasattr(object, name) 函数:
判断一个对象里面是否有name属性或者name方法,返回bool值,有name属性返回True,否则返回False。
注意: name要用括号括起来。
class function_demo():
name = 'demo'
def run(self):
return "hello function" functiondemo = function_demo()
res = hasattr(functiondemo, 'name') #判断对象是否有name属性,True res = hasattr(functiondemo, "run") #判断对象是否有run方法,True res = hasattr(functiondemo, "age") #判断对象是否有age属性,Falsw
print(res)
getattr(object, name[,default]) 函数:
获取对象object的属性或者方法,如果存在则打印出来,如果不存在,打印默认值,默认值可选。
注意:如果返回的是对象的方法,则打印结果是:方法的内存地址,如果需要运行这个方法,可以在后面添加括号()
class function_demo():
name = 'demo'
def run(self):
return "hello function" functiondemo = function_demo()
getattr(functiondemo, 'name') #获取name属性,存在就打印出来--- demo getattr(functiondemo, "run") #获取run方法,存在打印出 方法的内存地址---<bound method function_demo.run of <__main__.function_demo object at 0x10244f320>> getattr(functiondemo, "age") #获取不存在的属性,报错如下:
Traceback (most recent call last):
File "/Users/liuhuiling/Desktop/MT_code/OpAPIDemo/conf/OPCommUtil.py", line 39, in <module>
res = getattr(functiondemo, "age")
AttributeError: 'function_demo' object has no attribute 'age' getattr(functiondemo, "age", 18) #获取不存在的属性,返回一个默认值
setattr(object, name,values) 函数:
给对象的属性赋值,若属性不存在,先创建再赋值。
class function_demo():
name = 'demo'
def run(self):
return "hello function" functiondemo = function_demo()
res = hasattr(functiondemo, 'age') # 判断age属性是否存在,False
print(res) setattr(functiondemo, 'age', 18 ) #对age属性进行赋值,无返回值 res1 = hasattr(functiondemo, 'age') #再次判断属性是否存在,True
print(res1)
综合使用:
class function_demo():
name = 'demo'
def run(self):
return "hello function" functiondemo = function_demo()
res = hasattr(functiondemo, 'addr') # 先判断是否存在
if res:
addr = getattr(functiondemo, 'addr')
print(addr)
else:
addr = getattr(functiondemo, 'addr', setattr(functiondemo, 'addr', '北京首都'))
#addr = getattr(functiondemo, 'addr', '河南许昌')
print(addr)
python中 and和or的用法:
python中的and从左到右计算表达式,若所有值为真,则返回最后一个值,若存在假,返回第一个假值。
or 也是从左到右计算表达式,返回第一个为真的值。
# a 与b 均为真,返回最后一个为真的值,返回b的值
a = 1
b = 2
print(a and b) >>>> 2 # c 与 d 有一个为假,返回第一个为假的值,返回c的值
c = 0
d = 2
print(c and d) >>>>>0 # e 与f 均为真,返回第一个 为真的值,返回e的结果
e = 1
f = 2
print(e or f) >>>>>>1 # g 与h 为假,返回第一个 为真的值,返回h的结果
g= ''
h=1
print(g or h) >>>>>1
类似三目表达式的用法:bool? a : b
a ='first'
b ='second'
1and a or b # 等价于 bool = true时的情况,a与b均为真
'first'
>>>0and a or b # 等价于 bool = false时的情况
'second'
>>> a =''
>>>1and a or b # a为假时,则出现问题
'second'
>>>(1and[a]or[b])[0]# 安全用法,因为[a]不可能为假,至少有一个元素
python eval() hasattr() getattr() setattr() 函数使用方法详解的更多相关文章
- 【转】Python的hasattr() getattr() setattr() 函数使用方法详解
		Python的hasattr() getattr() setattr() 函数使用方法详解 hasattr(object, name)判断一个对象里面是否有name属性或者name方法,返回BOOL值 ... 
- Python的hasattr()  getattr() setattr() 函数使用方法详解
		hasattr(object, name)判断一个对象里面是否有name属性或者name方法,返回BOOL值,有name特性返回True, 否则返回False.需要注意的是name要用括号括起来 1 ... 
- Python的hasattr() getattr() setattr() 函数使用方法详解 (转)
		来自:https://www.cnblogs.com/cenyu/p/5713686.html hasattr(object, name)判断一个对象里面是否有name属性或者name方法,返回BOO ... 
- Python的hasattr() getattr() setattr() 函数使用方法详解--转载
		hasattr(object, name)判断一个对象里面是否有name属性或者name方法,返回BOOL值,有name特性返回True, 否则返回False.需要注意的是name要用括号括起来 1 ... 
- Python标准库:内置函数hasattr() getattr() setattr() 函数使用方法详解
		hasattr(object, name) 本函数是用来判断对象object的属性(name表示)是否存在.如果属性(name表示)存在,则返回True,否则返回False.参数object是一个对象 ... 
- Python的hasattr() getattr() setattr() 函数使用方法
		hasattr(object, name)判断一个对象里面是否有name属性或者name方法,返回BOOL值,有name特性返回True, 否则返回False.需要注意的是name要用括号括起来 &g ... 
- Python的hasattr() getattr() setattr() 函数使用方法(简介)
		hasattr(object, name)判断一个对象里面是否有name属性或者name方法,返回BOOL值,有name特性返回True, 否则返回False.需要注意的是name要用括号括起来 1 ... 
- hasattr() getattr() setattr() 函数使用方法
		1. hasattr(object, name) 判断object对象中是否存在name属性,当然对于python的对象而言,属性包含变量和方法:有则返回True,没有则返回False:需要注意的是n ... 
- 反射之hasattr() getattr() setattr() 函数
		Python的hasattr() getattr() setattr() 函数使用方法详解 hasattr(object, name)判断object中有没有一个name字符串对应的方法或属性,返回B ... 
随机推荐
- [Functional Programming Monad] Substitute State Using Functions With A State Monad (get, evalWith)
			We take a closer look at the get construction helper and see how we can use it to lift a function th ... 
- OpenCV 4.1 编译和配置
			OpenCV 4.0 版本,历时3年半,终于在2018年圣诞节前发布了,该版本增加的新功能如下: 1) 更新代码支持 c++11 特性,需要兼容 c++11 语法的编译器 2)增加 dnn 中的模块功 ... 
- iOS7重磅推新--不断尝试与重新设计的过程
			来源:GBin1.com iOS7重磅推新--不断尝试与重新设计的过程 或许你心里已经有了关于iPhone最新操作系统的评价,可能你喜欢它,也可能不喜欢,事实上大多数设计者不喜欢.设计界似乎一致认为I ... 
- 正则表达式:日期,电话,邮箱等常用字符串;js中日期的带下的比较,获取不同格式的日期
			一.日期 (1)首先需要验证年份,显然,年份范围为 0001 - 9999,匹配YYYY的正则表达式为: [0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1- ... 
- windows下at命令使用详解
			T命令是Windows XP中内置的命令,它也可以媲美Windows中的“计划任务”,而且在计划的安排.任务的管理.工作事务的处理方面,AT命令具有更强大更神通的功能.AT命令可在指定时间和日期.在指 ... 
- bin和sbin区别
			据说这个目录结构是沿袭unix的,不大清楚. bin是binary的缩写,是可执行的二进制文件./bin里面一般是基本的,大家都要用的工具:sbin里面的s是system的意思,是供system ad ... 
- [Exception IOS 4] - could not build module 'foundation'
			出现这个问题首先百度找到的是:http://www.cocoachina.com/bbs/read.php?tid=188086 然后在blog中能找到链接:http://stackoverflow. ... 
- 基于Netty的RPC简易实现
			代码地址如下:http://www.demodashi.com/demo/13448.html 可以给你提供思路 也可以让你学到Netty相关的知识 当然,这只是一种实现方式 需求 看下图,其实这个项 ... 
- leetcode——Lowest Common Ancestor of a Binary Tree
			题目 Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. 思路 这一次 ... 
- Paper Reading 1 - Playing Atari with Deep Reinforcement Learning
			来源:NIPS 2013 作者:DeepMind 理解基础: 增强学习基本知识 深度学习 特别是卷积神经网络的基本知识 创新点:第一个将深度学习模型与增强学习结合在一起从而成功地直接从高维的输入学习控 ... 
