理解 __getitem__ 方法 [英] Understanding __getitem__ method
问题描述
Python docs中__getitem__
的大部分文档我都看过了,但还是没能理解其中的含义.
I have gone through most of the documentation of __getitem__
in the Python docs, but I am still unable to grasp the meaning of it.
所以我能理解的是,__getitem__
用于实现像 self[key]
这样的调用.但是有什么用呢?
So all I can understand is that __getitem__
is used to implement calls like self[key]
. But what is the use of it?
假设我有一个以这种方式定义的 python 类:
Lets say I have a python class defined in this way:
class Person:
def __init__(self,name,age):
self.name = name
self.age = age
def __getitem__(self,key):
print ("Inside `__getitem__` method!")
return getattr(self,key)
p = Person("Subhayan",32)
print (p["age"])
这将按预期返回结果.但是为什么首先要使用 __getitem__
呢?我还听说 Python 在内部调用了 __getitem__
.但它为什么要这样做?
This returns the results as expected. But why use __getitem__
in the first place? I have also heard that Python calls __getitem__
internally. But why does it do it?
有人可以更详细地解释一下吗?
Can someone please explain this in more detail?
推荐答案
Cong Ma 很好地解释了 __getitem__
的用途 - 但我想给你一个可能有用的例子.想象一个对建筑物建模的类.在建筑物的数据中,它包括许多属性,包括对占据每一层楼的公司的描述:
Cong Ma does a good job of explaining what __getitem__
is used for - but I want to give you an example which might be useful.
Imagine a class which models a building. Within the data for the building it includes a number of attributes, including descriptions of the companies that occupy each floor :
如果不使用 __getitem__
我们会有这样的类:
Without using __getitem__
we would have a class like this :
class Building(object):
def __init__(self, floors):
self._floors = [None]*floors
def occupy(self, floor_number, data):
self._floors[floor_number] = data
def get_floor_data(self, floor_number):
return self._floors[floor_number]
building1 = Building(4) # Construct a building with 4 floors
building1.occupy(0, 'Reception')
building1.occupy(1, 'ABC Corp')
building1.occupy(2, 'DEF Inc')
print( building1.get_floor_data(2) )
然而,我们可以使用 __getitem__
(及其对应的 __setitem__
)来使 Building 类的使用更好".
We could however use __getitem__
(and its counterpart __setitem__
) to make the usage of the Building class 'nicer'.
class Building(object):
def __init__(self, floors):
self._floors = [None]*floors
def __setitem__(self, floor_number, data):
self._floors[floor_number] = data
def __getitem__(self, floor_number):
return self._floors[floor_number]
building1 = Building(4) # Construct a building with 4 floors
building1[0] = 'Reception'
building1[1] = 'ABC Corp'
building1[2] = 'DEF Inc'
print( building1[2] )
您是否像这样使用 __setitem__
实际上取决于您计划如何抽象数据 - 在这种情况下,我们决定将建筑物视为楼层的容器(并且您也可以实现迭代器对于建筑物,甚至可能具有切片能力 - 即一次获取多个楼层的数据 - 这取决于您的需求.
Whether you use __setitem__
like this really depends on how you plan to abstract your data - in this case we have decided to treat a building as a container of floors (and you could also implement an iterator for the Building, and maybe even the ability to slice - i.e. get more than one floor's data at a time - it depends on what you need.
这篇关于理解 __getitem__ 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!