程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python magic__ getitem__

編輯:Python

Python Magic __getitem__

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

  1. 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
    
  2. 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
    

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved