_ call _
call()的本質是將一個類變成一個函數(使這個類的實例可以像函數一樣調用)。
class A(object):
def __init__(self, name, age):
self.name = name
self.age = age
def __call__(self):
print('my name is %s' % self.name)
print('my age is %s' % self.age)
if __name__ == '__main__':
a = A('jack', 26)
a()
call模糊了函數和類的界限
class ClassA(object):
def __new__(cls, *args, **kwargs):
object = super(ClassA, cls).__new__(cls)
print("HHHA:0===>")
return object
def __init__(self, *args, **kwargs):
print("HHHB:0===>")
def __call__(self, func):
print("HHHC:0===>")
return func
A = ClassA()
print("HHHH:0====>")
@ClassA()
def hello():
print("HHHC:0===>hello")
print("HHHH:1====>")
hello()
HHHA:0===>
HHHB:0===>
HHHH:0====> //__call__()未調用
HHHA:0===>
HHHB:0===>
HHHC:0===> //__call__()被調用
HHHH:1====>
HHHC:0===>hello
zip
zip在英文中有拉鍊的意思,我們由此可以形象的理解它的作用:將可迭代的對象作爲參數,將對象中對應的元素打包成一個個元組,然後返回由這些元組組成的列表。如果各個迭代器的元素個數不一致,則返回列表長度與最短的對象相同。
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b) # 打包爲元組的列表
[(1, 4), (2, 5), (3, 6)]
>>> zip(a,c) # 元素個數與最短的列表一致
[(1, 4), (2, 5), (3, 6)]
>>> zip(*zipped) # 與 zip 相反,可理解爲解壓,爲zip的逆過程,可用於矩陣的轉置
[(1, 2, 3), (4, 5, 6)]
getattr()
getattr() 函數用於返回一個對象屬性值。
getattr 語法:
getattr(object, name[, default])
參數
object – 對象。
name – 字符串,對象屬性。
default – 默認返回值,如果不提供該參數,在沒有對應屬性時,將觸發 AttributeError。
返回值
返回對象屬性值。
例子
>>> class Student: # 定義類
def __init__(self,name,identity,age):
self._name = name
self._identity = identity
self.age = age
def __getitem__(self,item):
if isinstance(item,str):
return getattr(self,"_item")
>>> st=Student("Huang Lei",1323010212,12) # 實例化
>>> st["age"]
Traceback (most recent call last):
File "<pyshell#51>", line 1, in <module>
st["age"]
File "<pyshell#49>", line 8, in __getitem__
return getattr(self,"_item")
AttributeError: 'Student' object has no attribute '_item'
@staticmethod
當某個方法不需要用到對象中的任何資源,將這個方法改爲一個靜態方法, 加一個@staticmethod
加上之後, 這個方法就和普通的函數沒有什麼區別了, 只不過寫在了一個類中, 可以使用這個類的對象調用