class Tnt(object):
def __init__(self, num):
self.a = 0
self.num = num
def __setitem__(self, key, value):
print('setitem, key: ', key, type(key))
print('setitem, value: ', value, type(value))
self.a = value
def __getitem__(self, item):
print('getitem, item: ', item, type(item))
return self.a
def __add__(self, other):
print('--add--other', other.name)
return self.num + other.num
def __sub__(self, other):
print('--sub--other:', other.name)
return self.num - other.num
def __mul__(self, other):
print('--mul--other', other.name)
return self.num * other.num
def __contains__(self, item):
print('调用者--contains--self : ', self.name)
print('被调用者--contains--item : ', item.name)
return self.num < item.num
t1 = Tnt(10)
t1.name = 't1'
# t['1'] = 123 # t.__setitem__('1', 123)
print(t1['1'], '---') # t.__getitem__('1')
t2 = Tnt(5)
t2.name = 't2'
print(t1 - t2) # 结论 t1.__sub__(t2) ==> t1.num - t2.num
print(t1 in t2) # 结论 t2.__contains__(t1) ==> t2.num > t1.num
python: __setitem__, __getitem__,__contains__
最新推荐文章于 2024-10-26 19:00:16 发布