1 函數的預設值為mutable類型時的問題和解決辦法
def f2(a, L=[]):
L.append(a)
return L
print(f2(1))
print(f2(2))
print(f2(3))
def f3(a, L=None):
if L is None:
L = []
L.append(a)
return L
print(f3(1))
print(f3(2))
print(f3(3))
# the result will be
#[1]
#[1, 2]
#[1, 2, 3]
#[1]
#[2]
#[3] from copy import deepcopy
def resetDefaults(f):
defaults = f.__defaults__
def resetter(*args, **kwds):
f.__defaults__ = deepcopy(defaults)
return f(*args, **kwds)
resetter.__name__ = f.__name__
return resetter
@resetDefaults # This is how you apply a decorator
def TestDefaultCorrect(item, stuff = []):
stuff.append(item)
print (stuff)
TestDefaultCorrect(1)
# prints '[1]'
TestDefaultCorrect(2)
# prints '[2]', as expected
2 函數裝飾模式
def decorator1(func):
return lambda: func() + 1
def decorator2(func):
def print_func():
print (func())
return print_func
@decorator2
@decorator1
def function():
return 41
# to cal functions(), it is equal to call decorator2(decorator1(function))
function()
# prints '42'
3 檢查類型的屬性和方法是否存在
class Class:
answer = 42
getattr(Class, 'answer')
# returns 42
getattr(Class, 'question', 'What is six times nine?')
# returns 'What is six times nine?'
getattr(Class, 'question')
# raises AttributeError
4 動態修改類中的函數
class Class:
def method(self):
print ('Hey a method' )
instance = Class()
instance.method()
# prints 'Hey a method'
def new_method(self):
print ('New method wins!')
Class.method = new_method
instance.method()
# prints 'New method wins!'
5 類的靜態方法的使用
class Class:
@classmethod
def a_class_method(cls):
print ('I was called from class %s' % cls)
@staticmethod
def a_static_method():
print ('I have no idea where I was called from')
def another_static_method():
print ('I have no idea where I was called from2')
def an_instance_method(self):
print ('I was called from the instance %s' % self)
instance = Class()
Class.a_class_method()
instance.a_class_method()
# both print 'I was called from class __main__.Class'
Class.a_static_method()
instance.a_static_method()
# both print 'I have no idea where I was called from'
Class.another_static_method()
# both print 'I have no idea where I was called from2'
#instance.another_static_method()
#TypeError: another_static_method() takes no arguments (1 given)
#Class.an_instance_method()
# TypeError: an_instance_method() takes exactly 1 positional argument (0 given)
instance.an_instance_method()
# prints something like 'I was called from the instance <__main__.Class instance at 0x2e80d0>'
6 使用main來作為python檔案的入口
if __name__ == "__main__":
7 將函數的輸出重新導向到檔案 (以下代碼有個bug)
import sys
def stdoutToFile(filename, function, args ):
oldStdout = sys.stdout
f = open(filename, "w" )
sys.stdout = f
function(args)
#sys.stdout.flush()
#f.close()
sys.stdout = oldStdout
if __name__=='__main__':
print("modules")
stdoutToFile("modules.txt", help, "modules")
print("builtins")
stdoutToFile("builtins.txt", help, "builtins")
print("keywords")
stdoutToFile("keyword.txt", help, "keywords")
參考:http://www.siafoo.net/article/52#id26
完!