gll89的个人博客分享 http://blog.sciencenet.cn/u/gll89

博文

[转载]__getitem__ in python

已有 1416 次阅读 2019-5-15 19:06 |个人分类:Python|系统分类:科研笔记|文章来源:转载

1. 首先说一下私有变量 (private variable)

    a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member).


    __getitem__ is used to implement calls like self[key]


    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 :

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) )

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] )

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.


https://stackoverflow.com/questions/43627405/understanding-getitem-method



https://blog.sciencenet.cn/blog-1969089-1179222.html

上一篇:DICOM & its operation with python
下一篇:Atom如何使用go to definition
收藏 IP: 60.191.2.*| 热度|

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-4-30 19:26

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部