1. 程式人生 > >Python3基礎 __len__,__getitem__ 記錄列表中元素訪問的次數 定制不可變序列,下標字典

Python3基礎 __len__,__getitem__ 記錄列表中元素訪問的次數 定制不可變序列,下標字典

2.4 ubunt tip exit str nbsp cnblogs 4.5 python

?

  • python : 3.7.0
  • OS : Ubuntu 18.04.1 LTS
  • IDE : PyCharm 2018.2.4
  • conda : 4.5.11
  • type setting : Markdown

?

code

"""
@Author : 行初心
@Date   : 18-9-23
@Blog   : www.cnblogs.com/xingchuxin
@GitHub : github.com/GratefulHeartCoder
"""


# 定義一個不可變的序列,需要定義兩個方法
# 1 __len__(self)
# 2 __getitem__(self,key)
class MyList:
    def __init__(self, *args):
        # 列表推導式,很好用
        self.values = [x for x in args]
        # 生成一個下標為key,值全為0的字典。可以記錄訪問次數
        self.count = {}.fromkeys(range(len(self.values)), 0)

    def __len__(self):
        # 當使用len函數的時候,會調用這個
        print(‘容器的長度是:‘)
        return len(self.values)

    def __getitem__(self, key):
        # 當用索引來訪問元素的時候,會使用這個函數
        self.count[key] += 1
        return self.values[key]


def main():
    test = MyList(1, 2, 3, 4, 5, 6, 7)
    print(test.count)

    print(test[1])

    print(test.count)

    print(len(test))


if __name__ == ‘__main__‘:
    main()

?

result

/home/xcx/anaconda3/envs/xingchuxin/bin/python /home/xcx/PycharmProjects/oop/demo.py
{0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0}
2
{0: 0, 1: 1, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0}
容器的長度是:
7

Process finished with exit code 0

?

resource

  • [文檔] https://docs.python.org/3/
  • [規範] https://www.python.org/dev/peps/pep-0008/
  • [規範] https://zh-google-styleguide.readthedocs.io/en/latest/google-python-styleguide/python_language_rules/
  • [源碼] https://www.python.org/downloads/source/
  • [ PEP ] https://www.python.org/dev/peps/
  • [平臺] https://www.cnblogs.com/

?

tips

行初心 會根據所學的知識,對博文進行更新。
該博文地址:https://www.cnblogs.com/xingchuxin/p/9695483.html

?


Python具有開源、跨平臺、解釋型、交互式等特性,值得學習。
Python的設計哲學:優雅,明確,簡單。提倡用一種方法,最好是只有一種方法來做一件事。
代碼的書寫要遵守規範,這樣有助於溝通和理解。
每種語言都有獨特的思想,初學者需要轉變思維、踏實踐行、堅持積累。

Python3基礎 __len__,__getitem__ 記錄列表中元素訪問的次數 定制不可變序列,下標字典