python 技巧视频教程_扣丁学堂Python视频教程之Python开发技巧
扣丁學堂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在線學習
總結
以上是生活随笔為你收集整理的python 技巧视频教程_扣丁学堂Python视频教程之Python开发技巧的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 浙大计算机学院
- 下一篇: 【TOOLS】python3利用SMTP