Skip to content
Minsing Log
Go back

English Edition

Python getter โ†’ What Is __getitem__?

Programming & CS

__getitem__ is a method in Python that is called when an object is indexed (obj[key]) or sliced (obj[start:stop]). Defining this method inside a class allows instances of that class to be used like lists or dictionaries.


๐Ÿ“Œ Basic Usage

class MyList:
    def __init__(self, data):
        self.data = data

    def __getitem__(self, index):
        print(f"Called with index: {index}")
        return self.data[index]

my_list = MyList([10, 20, 30])
print(my_list[1])  # => Called with index: 1
                   # => 20

๐ŸŽฏ Key Features


โœ… Slicing Can Also Be Supported

class MyList:
    def __init__(self, data):
        self.data = data

    def __getitem__(self, index):
        print(f"Index received: {index}")
        return self.data[index]

lst = MyList([1, 2, 3, 4, 5])
print(lst[1:4])  # ์Šฌ๋ผ์ด์Šค ๊ฐ์ฒด(slice(1,4,None))๊ฐ€ ์ „๋‹ฌ๋จ

๐Ÿ“ฆ Example: Mimicking a Two-Dimensional Array

class Matrix:
    def __init__(self, rows):
        self.rows = rows

    def __getitem__(self, index):
        return self.rows[index]

m = Matrix([[1, 2], [3, 4]])
print(m[0][1])  # 2

โš ๏ธ Notes

If youโ€™re curious, I can also explain __setitem__ and __delitem__. Would you like to learn more?

๊ณต๊ฐœ ์—ฌ์ • ๊ตฌ๋…

๊ธ€์ด ์˜ฌ๋ผ์˜ค๋ฉด ์ด๋ฉ”์ผ๋กœ ๋ณด๋‚ด๋“œ๋ฆด๊ฒŒ์š”.

๊ฐœ๋ฐœ, ์ฐฝ์—…, ๋ฐฐ์›€, ์‹คํŒจ์™€ ํšŒ๊ณ ๋ฅผ ์งง๊ณ  ์†”์งํ•˜๊ฒŒ ๊ธฐ๋กํ•ฉ๋‹ˆ๋‹ค. ๊ฒ€์ƒ‰์œผ๋กœ ์Šค์ณ๊ฐ€๋Š” ๋…์ž๊ฐ€ ์•„๋‹ˆ๋ผ ์—ฌ์ •์„ ๋”ฐ๋ผ์˜ค๋Š” ํŒฌ์„ ๋งŒ๋“ค๊ธฐ ์œ„ํ•œ ๋‰ด์Šค๋ ˆํ„ฐ์ž…๋‹ˆ๋‹ค.

๋‰ด์Šค๋ ˆํ„ฐ๋Š” ์ค€๋น„ ์ค‘์ž…๋‹ˆ๋‹ค. ๊ทธ๋™์•ˆ RSS ๋กœ ๊ตฌ๋…ํ•˜๊ฑฐ๋‚˜ ์ด๋ฉ”์ผ ๋กœ ์•Œ๋ฆผ์„ ์š”์ฒญํ•ด ์ฃผ์„ธ์š”.


Share this post:

Comments

Sign in with GitHub to leave a comment.


Previous Post
Mean pooling - Let's match the embedding dimensions
Next Post
How to Map a Func to Elements of Multiple Nested Data Structures