1忽你、自Python2.2以后幼东,對類和類型進行了統(tǒng)一,做法就是將int()科雳、float()根蟹、str()、list()糟秘、tuple()這些BIF轉換為工廠函數简逮。請問所謂的工廠函數,其實是什么原理尿赚?
答:工廠函數散庶,其實就是一個類對象蕉堰。當你調用他們的時候,事實上就是創(chuàng)建一個相應的實例對象悲龟。
# a 和 b 是工廠函數(類對象)int的實例對象
>>> a = int('123')
>>> b = int('345')
>>> a + b
468
2屋讶、當實例對象進行加法操作時,會自動調用什么魔法方法须教?
答:對象a和b相加時(a+b)皿渗,Python會自動根據對象a的__add__魔法方法進行加法操作。
3轻腺、下邊的代碼有問題嗎乐疆?(運行起來似乎沒出錯呀)
class Foo:
def foo(self):
self.foo = 'I love FishC.com'
return self.foo
>>> foo = Foo()
>>> foo.foo()
'I love FishC.com'
答:這絕對是一個溫柔的陷阱,這種bug比較難以排查贬养,所以一定要注意:類的屬性名和方法名絕對不能相同挤土!如果代碼這么寫,就會有一個難以排查的bug出現了:
class Foo:
def __init__(self):
self.foo = 'I love FishC.com'
def foo(self):
return self.foo
>>> foo = Foo()
>>> foo.foo()
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
foo.foo()
TypeError: 'str' object is not callable
4误算、寫出下列運算符對應的魔法方法仰美。
運算符 | 對應的魔法方法 |
---|---|
+ | __add__(self,other) |
- | __sub__(self,other) |
* | __mul__(self,other) |
/ | __truediv__(self,other) |
// | __floordiv__(self,other) |
% | __mod__(self,other) |
divmod(a,b) | __divmod__(a,b) |
** | __pow__(self,other[,modulo]) |
<< | __lshift__(self,other) |
>> | __rshift__(self,other) |
& | __and__(self,other) |
^ | __xor__(self,other) |
| | __or__(self,other) |
5、以下代碼說明Python支持什么風格尉桩?
def calc(a,b,c):
return (a + b) * c
>>> a = calc(1,2,3)
>>> b = calc([1,2,3,],[4,5,6],2)
>>> c = calc('love','FishC',3)
>>> print(a)
9
>>> print(b)
[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6]
>>> print(c)
loveFishCloveFishCloveFishC
答:說明Python支持鴨子類型(duck typing)風格筒占。
練習
1、我們都知道在Python中蜘犁,兩個字符串相加會拼接字符串翰苫,但遺憾的是兩個字符串相減卻會拋出異常。因此这橙,現在我們要求定義一個Nstr類奏窑,支持字符串的相減操作:A-B,從A中去除所有B的子字符串屈扎。
示例:
>>> a = Nstr('I love FishC.com!iiiiiiii')
>>> b = Nstr('i')
>>> a - b
'I love FshC.com!'
答:只需要重載__sub__魔法方法即可埃唯。
class Nstr(str):
def __sub__(self,other):
return self.replace(other,'')
2、移位操作符是應用于二進制操作數的鹰晨,現在需要你定義一個新的類Nstr墨叛,也支持移位操作符的運算:
>>> a = Nstr('I love FishC.com!' )
>>> a << 3
'ove FishC.com!I l'
>>> a >> 3
'I love FishC.com!'
答:只需要重載__lshift__和__rshift__魔法方法即可。
class Nstr(str):
def __lshift__(self,other):
return self[other:] + self[:other]
def __rshift__(self,other):
return self[:-other] + self[-other:]
3模蜡、定義一個類Nstr,當該類的實例對象間發(fā)生的加漠趁、減、乘忍疾、除運算時闯传,將對象所有字符串的ASCⅡ碼之和進行計算:
>>> a = Nstr('FishC')
>>> b = Nstr('love')
>>> a + b
899
>>> a - b
23
>>> a * b
201918
>>> a / b
1.052511415525114
>>> a // b
1
代碼清單:
class Nstr:
def __init__(self,arg=''):
if isinstance(arg,str):
self.total = 0
for each in arg:
self.total += ord(each)
else:
print('參數錯誤!')
def __add__(self,other):
return self.total + other.total
def __sub__(self,other):
return self.total - other.total
def __mul__(self,other):
return self.total * other.total
def __truediv__(self,other):
return self.total / other.total
def __floordiv__(self,other):
return self.total // other.total