特殊方法和运算符重载

运算符重载

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'>]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值