
特殊方法和运算符重载
Python 的运输符实际上是通过调用对象的特殊方法实现的
a = 10
b = 10
c = a + b
d = a.__add__(b)
print('c=',c)
print('d=',d)
特殊方法
__setitem__
索引赋值a[key]=value
运算符方法
# 运算符的重载
class Student:
def __init__(self,name):
self.name = name
p1 = Student('小明')
p2 = Student('小红2')
x = p1 + p2
print(x)
# 运算符的重载
class Student:
def __init__(self,name):
self.name = name
def __add__(self,other):
if isinstance(other, Student):
return "{0}--{1}".format(self.name,other.name)
else:
return "不是同类对象,不能相加"
p1 = Student('小明')
p2 = Student('小红2')
x = p1 + p2
print(x)
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)