【坚持】Selenium+Python学习记录 DAY9

2018/05/29

[来源:菜鸟教程](http://www.runoob.com/python3/python3-examples.html

运算符重载

https://segmentfault.com/a/1190000013456795
https://zhuanlan.zhihu.com/p/20584316
[这个解释比较通俗易懂](https://zhidao.baidu.com/question/518493416493800005.html

#No.1
class Vector:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __str__(self):
        return 'Vector (%d, %d)' % (self.a, self.b)

    def __add__(self, other):
        return Vector(self.a + other.a, self.b + other.b)

v1 = Vector(2, 10)
v2 = Vector(5, -2)
print(v1 + v2)
resut:
d:\fly\Python (master -> origin)
λ python test.py
Vector (7, 8)
#No.2 <-- 还没理解
class A(object):
    def __add__(self, other):
        print('A.__add__')
        print(id(other))

class B(object):
    def __radd__(self, other):
        print('B.__radd__')
        print(id(other))

a = A()
b = B()
c = object()
print(id(a), id(b), id(c))
a + c
c + b
a + b
resut:
d:\fly\Python (master -> origin)
λ python test.py
2847569498912 2847569499584 2847567368352
A.__add__
2847567368352
B.__radd__
2847567368352
A.__add__
2847569499584

猜你喜欢

转载自www.cnblogs.com/flyin9/p/9108977.html