特殊函数一般以__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. CVE-2017-7269—IIS 6.0 WebDAV远程代码执行漏洞分析

    漏洞描述: 3月27日,在Windows 2003 R2上使用IIS 6.0 爆出了0Day漏洞(CVE-2017-7269),漏洞利用PoC开始流传,但糟糕的是这产品已经停止更新了.网上流传的poc ...

  2. JS中地址栏参数的获取

    function getParamer(paramer) { var url = window.location.href.split("?")[1]; /* 获取url里&quo ...

  3. Java字符串池

    1. String类的两个构造方法 private final char value[]; private int hash; public String() { this.value = " ...

  4. [转载]for循环的执行顺序

    原文地址:for循环的执行顺序作者:想飞上天的美人鱼   for循环的执行顺序用如下表达式: for(expression1;expression2;expression3) { expression ...

  5. [转]JSONObject,JSONArray使用手册

    您的评价:          收藏该经验       这两个是官网的API JSONObject API JSONArray API 里面有这两个类的所有方法,是不可多得的好材料哦~ 配合上面的API ...

  6. Codeforces Beta Round #7 D. Palindrome Degree hash

    D. Palindrome Degree 题目连接: http://www.codeforces.com/contest/7/problem/D Description String s of len ...

  7. Codeforces Round #194 (Div. 1) B. Chips 水题

    B. Chips Time Limit: 20 Sec  Memory Limit: 256 MB 题目连接 http://codeforces.com/contest/333/problem/B D ...

  8. C# winform 禁止窗体移动

    #region 禁止窗体移动 public const int WM_SYSCOMMAND = 0x112; public const int SC_MOVE = 0xF012; protected ...

  9. Single transistor provides short-circuit protection

    In certain dc/dc-converter applications, on-chip, cycle-by-cycle current limit may be insufficient p ...

  10. 对jQuery的事件绑定的一些思考

    jQuery的事件绑定 问题 首先我们看下面的一个非经常见的事件绑定代码: //example $('#dom').click(function(e){ //do something }); $('# ...