运算符重载
Python的运算符实际上是通过调用对象的特殊方法实现的。
a = 20
b = 30
c = a+b
d = a.__add__(b)
print("c=",c)
print("d=",d)
结果:
c= 50
d= 50
方法 | 说明 | 例子 |
---|---|---|
__init__ | 构造方法 | 对象创建:p = Person() |
__del__ | 析构方法 | 对象回收 |
__repr__,__str__ | 打印,转换 | print(a) |
__call__ | 函数调用 | a() |
__getattr__ | 点号运算 | a.xxx |
__setattr__ | 属性赋值 | a.xxx = value |
__getitem__ | 索引运算 | a[key] |
__setitem__ | 索引赋值 | a[key]=value |
__len__ | 长度 | len(a) |
每个运算符实际上都对应了相应的方法,统计如下:
运算符 | 特殊方法 | 说明 |
---|---|---|
运算符+ | __add__ | 加法 |
运算符- | __sub__ | 减法 |
<,<=,== | __lt__,__le__,__eq__ | 比较运算符 |
>,>=,!= | __gt__,__ge__,__ne__ | 比较运算符 |
,^,& | __or__,__xor__,__and__ | 或、异或、与 |
<<,>> | __lshift__,__rshift__ | 左移、右移 |
*,/,%,// | __mul__,__truediv__,__mod__,__floordiv__ | 乘、浮点除、模运算(取余)、整数除 |
** | pow | 指数运算 |
class Counter:
def __init__(self,x):
self.x = x
def __add__(self, other): #如果注释该方法,下面的‘+’运算报错
if isinstance(other,Counter):
return self.x + other.x
def __mul__(self, other):
if isinstance(other,Counter):
return self.x * other.x
x = Counter(5)
y = Counter(4)
print(x + y)
print(x * y)
特殊属性
Python 对象中包含了很多双下划线开始和结束的属性,这些是特殊属性,有特殊用法。常见的特殊属性:
特殊方法 | 含义 |
---|---|
obj.__dict__ | 对象的属性字典 |
obj.__class__ | 对象所属的类 |
class.__bases__ | 类的基类元组(多继承) |
class.__base__ | 类的基类 |
class.__mro__ | 类层次结构 |
class.__subclasses__() | 子类列表 |
class A:
pass
class B:
pass
class C(B,A):
def __init__(self,nn):
self.nn = nn
def cc(self):
print("cc")
c = C(3)
print(dir(c))
print(c.__dict__)
print(c.__class__)
print(C.__bases__)
print(C.mro())
print(A.__subclasses__())
结果:
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'cc', 'nn']
{'nn': 3}
<class '__main__.C'>
(<class '__main__.B'>, <class '__main__.A'>)
[<class '__main__.C'>, <class '__main__.B'>, <class '__main__.A'>, <class 'object'>]
[<class '__main__.C'>]