特殊函数一般以__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

Python类,特殊方法, __getitem__,__len__, __delitem__的更多相关文章

  1. python类及其方法

    python类及其方法 一.介绍 在 Python 中,面向对象编程主要有两个主题,就是类和类实例类与实例:类与实例相互关联着:类是对象的定义,而实例是"真正的实物",它存放了类中 ...

  2. Python类,域,方法,对象,继承

    类和对象: 是面向对象编程的两个主要方面,类创建一个新类型,而对象这个类的实例.. 域: 属于一个对象或类的变量被称为域.域有两种类型: 属于每个实例(类的对象)或属于类本身.它们分别被称为实例变量和 ...

  3. python中函数和方法区别,以及如何给python类动态绑定方法和属性(涉及types.MethodType()和__slots__)

    网上有很多同义但不同方式的说法,下面的这个说法比较让你容易理解和接受 与类和实例无绑定关系的function都属于函数(function): 与类和实例有绑定关系的function都属于方法(meth ...

  4. Python 类中方法的内部变量,命名加'self.'变成 self.xxx 和不加直接 xxx 的区别

    先看两个类的方法: >>> class nc(): def __init__(self): self.name ='tester' #name变量加self >>> ...

  5. 第8.7节 Python类__new__方法和构造方法关系深入剖析:__new__方法执行结果对__init__的影响案例详解

    一. 引言 前面章节介绍了类中的构造方法和__new__方法,并分析了二者执行的先后顺序关系.__new__方法在__init__方法前执行,__new__方法执行后才返回实例对象,也就是说__new ...

  6. python - 类的方法

    类的方法分为:普通方法. 静态方法和类方法   调用方式 特征 普通方法 由对象去调用执行,属于类 至少一个self,对象调用 静态方法 属于类,但通过类来调用,不依赖于任何对象,方法内部不需要对象封 ...

  7. python 类和方法(面向对象)

    类和方法 name = "Jack" city = "bejing" print("my name is %S and come from %s &q ...

  8. python类内部方法__setattr__ __getattr_ __delattr__ hasattr __getattribute__ __getitem__(),__setitem__(), __delitem__()

    主要讲类的内部方法 __setattr__  __getattr_  __delattr__  hasattr  __getattribute__  __getitem__(),__setitem__ ...

  9. Method Resolution Order – Python类的方法解析顺序

    在支持多重继承的编程语言中,查找方法具体来自那个类时的基类搜索顺序通常被称为方法解析顺序(Method Resolution Order),简称MRO.(Python中查找其它属性也遵循同一规则.)对 ...

  10. python类中方法加单下划线、双下划线、前后双下滑线的区别

    首先看一段代码: class Foo(): def __init__(self): print "__init__ method" def public_method(self): ...

随机推荐

  1. [BZOJ5334][TJOI2018]数学计算(exgcd/线段树)

    模意义下除法若结果仍为整数的话,可以记录模数的所有质因子,计算这些质因子的次幂数,剩余的exgcd解决. $O(n\log n)$但有9的常数(1e9内的数最多有9个不同的质因子),T了. #incl ...

  2. Android演示Stack(课下作业)

    Demand 之前活动中误传成别的截图,故在此补充博客 1.使用自己实现的栈构建Android程序,提供用于栈的一个puh按钮和pop按钮,在文本域接收一个字符串作为push的输入,文本区将显示每个操 ...

  3. python中后端数据序列化不显示中文的解决方法

    我们在前后端交互的时候,让序列化的数据更友好的显示,我们会用到 import json js = json.loads('{"name": "多多"}') pr ...

  4. python3-开发进阶Flask的基础

    一.概述 最大的特点:短小精悍.可拓展强的一个Web框架.注意点:上下文管理机制,依赖wsgi:werkzurg 模块 二.前奏学习werkzurg 先来回顾一个知识点:一个类加括号会执行__init ...

  5. Codeforces Round #299 (Div. 1) A. Tavas and Karafs 水题

    Tavas and Karafs Time Limit: 1 Sec  Memory Limit: 256 MB 题目连接 http://codeforces.com/contest/536/prob ...

  6. img 边距的问题

    一.*{margin:0;padding:0} 不能消除img的边距 二.布局中可以使用以下方法: 1.img:{flot:left} 2.img:{vertical-align: top;}  im ...

  7. 自定义的tabBarController的几种方法

    本文转载自:http://blog.sina.com.cn/s/blog_79c5bdc30100t88i.html 我自己实现的一种可以很方便的实现更换TabBarController图片的方法,代 ...

  8. How to open a web site with the default web browser in a NEW window

    http://delphi.about.com/cs/adptips2004/a/bltip0504_4.htm When using ShellExecute (as explained in th ...

  9. [转].net reactor 学习系列(二)---.net reactor界面各功能说明

    安装了.net reactor之后,可以在安装目录下找到帮助文档REACTOR_HELP.chm,目前没有中文版本,里面详细介绍了.net reactor的各功能及使用场景.本系列文章是基于此帮助文档 ...

  10. React的第一个例子

    准备: 官网:https://facebook.github.io/react/downloads.html Github地址:https://github.com/facebook/react 首先 ...