python学习高级篇(part8)--类对象的特殊方法
生活随笔
收集整理的這篇文章主要介紹了
python学习高级篇(part8)--类对象的特殊方法
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
學(xué)習(xí)筆記,僅供參考,有錯必糾
文章目錄
- python 學(xué)習(xí)高級篇
- 類對象的特殊方法之`__iter__()`和`__next__()`
- 類對象的特殊方法之`__add__()`和`__radd__()`
python 學(xué)習(xí)高級篇
# 支持多行輸出 from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = 'all' #默認(rèn)為'last'類對象的特殊方法之__iter__()和__next__()
L = [1, 2, 3, 4, 5]for item in L:print(item) 1 2 3 4 5for-in語句在默認(rèn)情況下不能用于自定義類對象的實例對象
class MyClass(object):passfor item in MyClass(): # TypeError: 'MyClass' object is not iterableprint(item) ---------------------------------------------------------------------------TypeError Traceback (most recent call last)<ipython-input-2-4128e49c4e9a> in <module>()2 pass3 ----> 4 for item in MyClass(): # TypeError: 'MyClass' object is not iterable5 print(item)TypeError: 'MyClass' object is not iterable class MyClass(object):def __init__(self):self.data = 0def __iter__(self):return selfdef __next__(self):if self.data > 5:raise StopIteration()else:self.data += 1return self.datafor item in MyClass():print(item) 1 2 3 4 5 6類對象的特殊方法之__add__()和__radd__()
標(biāo)準(zhǔn)算術(shù)運算符在默認(rèn)情況下不能用于自定義類對象的實例對象
class MyClass1(object):passclass MyClass2(object):passprint(MyClass1() + MyClass2()) ---------------------------------------------------------------------------TypeError Traceback (most recent call last)<ipython-input-5-eff96f1ce3ef> in <module>()5 pass6 ----> 7 print(MyClass1() + MyClass2())TypeError: unsupported operand type(s) for +: 'MyClass1' and 'MyClass2'如果想讓標(biāo)準(zhǔn)算術(shù)運算符可以用于自定義類對象的實例對象,必須在自定義類對象中實現(xiàn)標(biāo)準(zhǔn)算術(shù)運算符對應(yīng)的以下特殊方法:
之所以可以使用加法和乘法運算符操作列表,是因為列表所對應(yīng)的類對象list中實現(xiàn)了+和*對應(yīng)的特殊方法;
之所以可以使用加法和乘法運算符操作字符串,是因為字符串所對應(yīng)的類對象str中實現(xiàn)了+和*對應(yīng)的特殊方法。
# 測試1 class C1(object):def __add__(self, other):print("特殊方法__add__被調(diào)用")return "xxx"# return NotImplementedclass C2(object):def __radd__(self, other):print("特殊方法__radd__被調(diào)用")return "yyy"# return NotImplementedobj1 = C1() obj2 = C2()print(obj1 + obj2) 特殊方法__add__被調(diào)用 xxx # 測試2 class C1(object):passclass C2(object):def __radd__(self, other):print("特殊方法__radd__被調(diào)用")return "yyy"# return NotImplementedobj1 = C1() obj2 = C2()print(obj1 + obj2) 特殊方法__radd__被調(diào)用 yyy # 測試3 class C1(object):def __add__(self, other):print("特殊方法__add__被調(diào)用")return NotImplementedclass C2(object):def __radd__(self, other):print("特殊方法__radd__被調(diào)用")return "yyy"# return NotImplementedobj1 = C1() obj2 = C2()print(obj1 + obj2) 特殊方法__add__被調(diào)用 特殊方法__radd__被調(diào)用 yyy
總結(jié)
以上是生活随笔為你收集整理的python学习高级篇(part8)--类对象的特殊方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 契税计算 如何计算契税
- 下一篇: websocket python爬虫_p