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]
@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 '
6 使用main来作为python文件的入口
if __name__ == "__main__":