扣丁学堂Python视频教程之Python开发技巧
2018-07-25 14:09:44
808浏览
关于Python开发的技巧小编在上篇文章已经给大家分享过一些,本篇文章扣丁学堂
神秘eval:
eval可理解为一种内嵌的python解释器(这种解释可能会有偏差), 会解释字符串为对应的代码并执行, 并且将执行结果返回。
看一下下面这个例子:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def test_first():
return 3
def test_second(num):
return num
action = { # 可以看做是一个sandbox
"para": 5,
"test_first" : test_first,
"test_second": test_second
}
def test_eavl():
condition = "para == 5 and test_second(test_first) > 5"
res = eval(condition, action) # 解释condition并根据action对应的动作执行
print res
if __name__ == '_
exec:
exec在Python中会忽略返回值, 总是返回None, eval会返回执行代码或语句的返回值
exec和eval在执行代码时, 除了返回值其他行为都相同
在传入字符串时, 会使用compile(source, '', mode)编译字节码。 mode的取值为exec和eval
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def test_first():
print "hello"
def test_second():
test_first()
print "second"
def test_third():
print "third"
action = {
"test_second": test_second,
"test_third": test_third
}
def test_exec():
exec "test_second" in action
if __name__ == '__main__':
test_exec() # 无法看到执行结果
getattr:
getattr(object, name[, default])返回对象的命名属性,属性名必须是字符串。如果字符串是对象的属性名之一,结果就是该属性的值。例如, getattr(x, ‘foobar’) 等价于 x.foobar。 如果属性名不存在,如果有默认值则返回默认值,否则触发 AttributeError 。
# 使用范例
class TestGetAttr(object):
test = "test attribute"
def say(self):
print "test method"
def test_getattr():
my_test = TestGetAttr()
try:
print getattr(my_test, "test")
except AttributeError:
print "Attribute Error!"
try:
getattr(my_test, "say")()
except AttributeError: # 没有该属性, 且没有指定返回值的情况下
print "Method Error!"
if __name__ == '__main__':
test_getattr()
以上就是扣丁学堂Python在线学习小编给大家分享的Python开发的技巧有哪些,希望对小伙伴们有所帮助,想要了解更多内容的小伙伴可以登录扣丁学堂官网咨询。想要学好Python开发小编给大家推荐口碑良好的扣丁学堂,扣丁学堂有专业老师制定的Python学习路线图辅助学员学习,此外还有与时俱进的Python课程体系和大量的Python视频教程供学员观看学习,想要学好Python开发技术的小伙伴快快行动吧。扣丁学堂Python技术交流群:279521237。
【关注微信公众号获取更多学习资料】
标签:
扣丁学堂Python视频教程
Python开发技巧
Python培训
Python视频教程
Python基础教程
python安装教程
Python核心编程
Python在线教程
Python在线视频
Python在线学习