class Foo: #构造方法 def __init__(self,name,age): pass self.name = name self.age = age def __str__(self): return "%s - %d" %(self.name,self.age)
obj1 = Foo(‘alex‘,73)obj2 = Foo(‘eric‘,84)print(obj1)
out:
alex - 73
__getitem__
class Foo: #构造方法 def __init__(self,name,age): pass self.name = name self.age = age def __getitem__(self, item): return 123 obj = Foo(‘alex‘,73) ret = obj[‘ab‘] print(ret)
out:
123
class Foo: #构造方法 def __init__(self,name,age): pass self.name = name self.age = age def __getitem__(self, item): print(item.start) print(item.stop) print(item.step) obj = Foo(‘alex‘,73) ret2 = obj[1:4:2]
out:
1
4
2
__setitem__
class Foo: #构造方法 def __init__(self,name,age): pass self.name = name self.age = age def __getitem__(self, item): return 123 def __setitem__(self, key, value): print(‘setitem‘) obj = Foo(‘alex‘,73) obj[‘k1‘] = 111
out:
setitem
class Foo: #构造方法 def __init__(self,name,age): pass self.name = name self.age = age def __setitem__(self, key, value): print(type(key),type(value)) print(key.start) print(key.stop) print(key.step) obj = Foo(‘alex‘,73) obj[1:4] = [11,22,33,44]
out:
<class ‘slice‘> <class ‘list‘> 1 4None
__delitem__
class Foo: #构造方法 def __init__(self,name,age): pass self.name = name self.age = age def __delitem__(self, key): print(‘del item‘) obj = Foo(‘alex‘,73) del obj[‘k1‘]
out:
del item
class Foo: #构造方法 def __init__(self,name,age): pass self.name = name self.age = age def __delitem__(self, key): print(type(key)) print(key.start) print(key.stop) print(key.step) obj = Foo(‘alex‘,73) del obj[1:4]
out:
<class ‘slice‘>
1
4
None
时间: 2024-10-10 09:20:39