# 下面的例子是關於調用“從未在類中定義過的函數”
>>> class X(object):
def __init__(self, arg1, arg2):
self.a1 = arg1
self.b1 = arg2
print "init"
def my_default(self):
print "my default function"
>>> x1 = X(1, 2)
init
>>> x1.func1() # 從未在類中定義過函數func1()
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-68-40c5f1565149> in <module>()
----> 1 x1.func1()
AttributeError: 'X' object has no attribute 'func1'
>>> x1.func2() # 從未在類中定義過函數func2()
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-69-bf53c3f763a9> in <module>()
----> 1 x1.func2()
AttributeError: 'X' object has no attribute 'func2'
>>>
>>> class X(object):
def __init__(self, arg1, arg2):
self.a1 = arg1
self.b1 = arg2
print "init"
# 當調用此類中未定義過的函數,且傳入了參數時,可以使用不定長參數*args
def my_default(self, *args):
print "my default function, you input argument: " + str(args[0])
# 當調用了不存在方法時,則會調用此 __getattr__
def __getattr__(self, other_func_name):
print "your are calling other function:", other_func_name
return self.my_default
>>> x2 = X(5, 6)
init
>>> x2.hello("good morning!")
your are calling other function: hello
my default function, you input argument: good morning!
>>> x2.OK(100,200)
your are calling other function: OK
my default function, you input argument: 100
# 高階函數,函數返回函數
>>> def my_func(n):
print "In my_func"
def inner_func(arg):
print "In inner_func"
return n * arg
return inner_func
>>> intermediate_func = my_func(10)
In my_func
>>> intermediate_func(3.5)
In inner_func
35.0
# ==========使用裝飾器實現單實例設計模式===========
# 裝飾器。從本質上說,裝飾器本質上也是一個python函數,它的作用是增強其他函數的功能(裝飾其他函數)
>>> def make_singleton(a_class):
instance_dict = dict()
def create_single_instance():
if a_class not in instance_dict:
# 當且僅當沒有此類的實例時,創建一個此類的實例
instance_dict[a_class] = a_class()
return instance_dict[a_class]
return create_single_instance
>>> # 使用裝飾器,直接放到其他對象的“頭上”
@make_singleton
>>> class MyClass(object):
from datetime import datetime
now_time = str(datetime.now())
def show_created_time(self):
return "created time was:", self.now_time
# 嘗試創建兩個對象
>>> obj1 = MyClass()
>>> obj2 = MyClass()
# 通過調用同一個方法查看是否創建於同一個時間點(也就是同一個實例)
>>> obj1.show_created_time()
('created time was:', '2018-05-11 17:10:40.666000')
>>> obj2.show_created_time()
('created time was:', '2018-05-11 17:10:40.666000')
# 檢查是否同一個對象,結果:是
>>> print id(obj1), id(obj2)
109425040 109425040
好了,就寫到這裏,看官們覺得漲知識了,請在文章左側點個贊 _