zoukankan      html  css  js  c++  java
  • Python类,特殊方法, __getitem__,__len__, __delitem__

    特殊函数一般以__methodname__的形式命名,如:__init__(构造方法), __getitem__、 __setitem__(subscriptable所需method), __delitem__(del obj[key]所需method), __len__(len(…)所需method)等;

    以下以什么都不做的Something类,结合lambda表达式,来说明这些特殊函数;

    >>> class Something:

    ... pass

    ...

    >>> s = Something()

    >>> s['key1']

    Traceback (most recent call last):

    File "<stdin>", line 1, in <module>

    TypeError: 'Something' object is not subscriptable

    subscriptable相关的函数是 __getitem__、 __setitem__,顾名思义,两者分别用于获取和设置相应的key的值;

    Something.__getitem__ = lambda self, key: key

    __getitem__简单的返回key;

    >>> s['key1']

    'key1'

    >>> s[1]

    1

    >>> s[(1,2,3)]

    (1, 2, 3)

    注意:不可变类,都可以作为key;

    >>> s[1] = 2

    Traceback (most recent call last):

    File "<stdin>", line 1, in <module>

    TypeError: 'Something' object does not support item assignment

    增加__setitem__方法,简单的打印key-value对;

    >>> Something.__setitem__ = lambda self, key, value: print(repr(key) + ":" + repr(value))

    >>> s[1] = 33

    1:33

    >>> s[(1,2,3)] = "333"

    (1, 2, 3):'333'

    >>> del s[1]

    Traceback (most recent call last):

    File "<stdin>", line 1, in <module>

    AttributeError: __delitem__

    增加__delitem__方法,简单打印

    >>> Something.__delitem__ = lambda self, key : print(repr(key) + " is deleted")

    >>> del s[23]

    23 is deleted

    >>> len(s)

    Traceback (most recent call last):

    File "<stdin>", line 1, in <module>

    TypeError: object of type 'Something' has no len()

    增加__len__方法,简单返回1

    >>> Something.__len__ = lambda self : 1

    >>> len(s)

    1

  • 相关阅读:
    web应用本质
    SQL逻辑查询语句执行顺序
    flask-WTForms组件
    生产者消费者模型
    单例模式
    flask中的信号量
    flask-script
    flask-session
    在python项目中导出项目依赖的模块信息
    Flask简介之简单应用
  • 原文地址:https://www.cnblogs.com/chjbbs/p/5740143.html
Copyright © 2011-2022 走看看