python 技巧视频教程_扣丁学堂Python视频教程之Python开发技巧
扣丁學(xué)堂Python視頻教程之Python開發(fā)技巧
2018-07-25 14:09:44
808瀏覽
關(guān)于Python開發(fā)的技巧小編在上篇文章已經(jīng)給大家分享過(guò)一些,本篇文章扣丁學(xué)堂
神秘eval:
eval可理解為一種內(nèi)嵌的python解釋器(這種解釋可能會(huì)有偏差), 會(huì)解釋字符串為對(duì)應(yīng)的代碼并執(zhí)行, 并且將執(zhí)行結(jié)果返回。
看一下下面這個(gè)例子:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def test_first():
return 3
def test_second(num):
return num
action = { # 可以看做是一個(gè)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并根據(jù)action對(duì)應(yīng)的動(dòng)作執(zhí)行
print res
if __name__ == '_
exec:
exec在Python中會(huì)忽略返回值, 總是返回None, eval會(huì)返回執(zhí)行代碼或語(yǔ)句的返回值
exec和eval在執(zhí)行代碼時(shí), 除了返回值其他行為都相同
在傳入字符串時(shí), 會(huì)使用compile(source, '', mode)編譯字節(jié)碼。 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() # 無(wú)法看到執(zhí)行結(jié)果
getattr:
getattr(object, name[, default])返回對(duì)象的命名屬性,屬性名必須是字符串。如果字符串是對(duì)象的屬性名之一,結(jié)果就是該屬性的值。例如, getattr(x, ‘foobar’) 等價(jià)于 x.foobar。 如果屬性名不存在,如果有默認(rèn)值則返回默認(rèn)值,否則觸發(fā) 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: # 沒(méi)有該屬性, 且沒(méi)有指定返回值的情況下
print "Method Error!"
if __name__ == '__main__':
test_getattr()
以上就是扣丁學(xué)堂Python在線學(xué)習(xí)小編給大家分享的Python開發(fā)的技巧有哪些,希望對(duì)小伙伴們有所幫助,想要了解更多內(nèi)容的小伙伴可以登錄扣丁學(xué)堂官網(wǎng)咨詢。想要學(xué)好Python開發(fā)小編給大家推薦口碑良好的扣丁學(xué)堂,扣丁學(xué)堂有專業(yè)老師制定的Python學(xué)習(xí)路線圖輔助學(xué)員學(xué)習(xí),此外還有與時(shí)俱進(jìn)的Python課程體系和大量的Python視頻教程供學(xué)員觀看學(xué)習(xí),想要學(xué)好Python開發(fā)技術(shù)的小伙伴快快行動(dòng)吧??鄱W(xué)堂Python技術(shù)交流群:279521237。
【關(guān)注微信公眾號(hào)獲取更多學(xué)習(xí)資料】
標(biāo)簽:
扣丁學(xué)堂Python視頻教程
Python開發(fā)技巧
Python培訓(xùn)
Python視頻教程
Python基礎(chǔ)教程
python安裝教程
Python核心編程
Python在線教程
Python在線視頻
Python在線學(xué)習(xí)
總結(jié)
以上是生活随笔為你收集整理的python 技巧视频教程_扣丁学堂Python视频教程之Python开发技巧的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。