The last article discussed
__call__
Magic methods , Let's talk about__getitem__
The wonder of .
Python Objects in are divided into iteratable objects and non iteratable objects , So what is an iteratable object ?
It can be said simply , have access to for i in obj
The traversal objects are all iteratable objects , Out-of-service for i in obj
Traversal is the non iterative object .
therefore range(n)、list、tuple、str、dict
And so on are iteratable objects , and int、float
With general Function object 、 Class object
And so on are non iteratable objects .
Iteratable objects are iteratable , It is because of the internal implementation __iter__
or __getitem__
Magic methods
If not defined __getitem__
class MyList:
def __init__(self,len:int):
self.list=[i for i in range(len)]
self.length=len
def __repr__(self)->str:
return f"MyList({
self.length}):{
self.list}"
x=MyList(10)
x[7]
The result is wrong , Show MyList
Cannot be accessed by subscript :
Traceback (most recent call last):
File "d:\Github-Projects\Crack_Detection_Daily\He\env.py", line 14, in <module>
x[7]
TypeError: 'MyList' object is not subscriptable
Definition __getitem__
after
from numpy import iterable
class MyList:
def __init__(self, len: int):
self.list = [i for i in range(len)]
self.length = len
def __getitem__(self, index: int) -> int:
return self.list[index]
def __repr__(self) -> str:
return f"MyList({
self.length}):{
self.list}"
x = MyList(10)
print(x[7])
print(x.__getitem__(7))
print(iterable(x))
print(x[7] is x.__getitem__(7))
for i in x:
print(i,end=' ')
notes :numpy.iterable(x)
Can be judged x Whether it is an iterative object
Output is :
7
7
True
True
0 1 2 3 4 5 6 7 8 9
thus it can be seen , adopt x[7]
Equivalent to x.__getitem__(7)
, That defines the __getitem__
Method can make this element an iteratable object , Can be accessed by subscript .
More Than This , Generally speaking, as long as it is an iterative object , Both x.__getitem__(y) <==> x[y]
, Dictionaries are no exception :
dic = {
'hjd': 'yyds',
'zyy': 'goddess'
}
print(dic.__getitem__('hjd'))
print(dic['hjd'])
print(dic['hjd'] is dic.__getitem__('hjd'))
result :
yyds
yyds
True