学习笔记,仅供参考,有错必纠
 
文章目录
- python 学习高级篇
 
- 类对象的特殊方法之`__iter__()`和`__next__()`
 - 类对象的特殊方法之`__add__()`和`__radd__()`
 
python 学习高级篇
# 支持多行输出
from IPython.core.interactiveshell import InteractiveShell 
InteractiveShell.ast_node_interactivity = 'all' #默认为'last' 
类对象的特殊方法之__iter__()和__next__()
L = [1, 2, 3, 4, 5]
for item in L:
    print(item)1
2
3
4
5for-in语句在默认情况下不能用于自定义类对象的实例对象
class MyClass(object):
    pass
for item in MyClass():  # TypeError: 'MyClass' object is not iterable
    print(item)---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-4128e49c4e9a> in <module>()
      2     pass
      3 
----> 4 for item in MyClass():  # TypeError: 'MyClass' object is not iterable
      5     print(item)
TypeError: 'MyClass' object is not iterable
class MyClass(object):
    def __init__(self):
        self.data = 0
    def __iter__(self):
        return self
    def __next__(self):
        if self.data > 5:
            raise StopIteration()
        else:
            self.data += 1
            return self.data
for item in MyClass():
    print(item)1
2
3
4
5
6 
类对象的特殊方法之__add__()和__radd__()
标准算术运算符在默认情况下不能用于自定义类对象的实例对象
class MyClass1(object):
    pass
class MyClass2(object):
    pass
print(MyClass1() + MyClass2())---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-eff96f1ce3ef> in <module>()
      5     pass
      6 
----> 7 print(MyClass1() + MyClass2())
TypeError: unsupported operand type(s) for +: 'MyClass1' and 'MyClass2'如果想让标准算术运算符可以用于自定义类对象的实例对象,必须在自定义类对象中实现标准算术运算符对应的以下特殊方法:

 
之所以可以使用加法和乘法运算符操作列表,是因为列表所对应的类对象list中实现了+和*对应的特殊方法;
之所以可以使用加法和乘法运算符操作字符串,是因为字符串所对应的类对象str中实现了+和*对应的特殊方法。
 

# 测试1
class C1(object):
    def __add__(self, other):
        print("特殊方法__add__被调用")
        return "xxx"
        # return NotImplemented
class C2(object):
    def __radd__(self, other):
        print("特殊方法__radd__被调用")
        return "yyy"
        # return NotImplemented
obj1 = C1()
obj2 = C2()
print(obj1 + obj2)特殊方法__add__被调用
xxx# 测试2
class C1(object):
    pass
class C2(object):
    def __radd__(self, other):
        print("特殊方法__radd__被调用")
        return "yyy"
        # return NotImplemented
obj1 = C1()
obj2 = C2()
print(obj1 + obj2)特殊方法__radd__被调用
yyy# 测试3
class C1(object):
    def __add__(self, other):
        print("特殊方法__add__被调用")
        return NotImplemented
class C2(object):
    def __radd__(self, other):
        print("特殊方法__radd__被调用")
        return "yyy"
        # return NotImplemented
obj1 = C1()
obj2 = C2()
print(obj1 + obj2)特殊方法__add__被调用
特殊方法__radd__被调用
yyy










