關於Python開發的技巧小編在上篇文章已經給大家分享過一些,本篇文章小編再和大家分享一下Python開發的技巧有哪些,下面隨小編一起來了解一下Python開發的技巧有哪些吧。
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()