最新消息:20210917 已从crifan.com换到crifan.org

【整理】Python 特殊方法 魔术方法

Python crifan 2033浏览 0评论

折腾:

Python __enter__和__exit__

Understanding Python’s “with” statement – {code that works} by Sadique Ali

-》

__enter__

__exit__

python __enter__

python __enter__ 与 __exit__的作用,以及与 with 语句的关系 – 李皮筋 – 博客园

Explaining Python’s ‘__enter__’ and ‘__exit__’ – Stack Overflow

Python深入02 上下文管理器 – Vamei – 博客园

“上下文管理器(context manager)是Python2.5开始支持的一种语法,用于规定某个对象的使用范围。一旦进入或者离开该使用范围,会有特殊操作被调用 (比如为对象分配或者释放内存)。它的语法形式是with…as…”

->只有用了with … as … 才会有 上下文管理器 -》才会有with要操作的对象,要支持 __enter__和__exit__

基于类的实现 · Python进阶

Python with解析 __enter__()、__exit__() (十五) – CSDN博客

浅谈 Python 的 with 语句

期间,看到的:

Python深入01 特殊方法与多范式 – Vamei – 博客园

Python一切皆对象,但同时,Python还是一个多范式语言(multi-paradigm),你不仅可以使用面向对象的方式来编写程序,还可以用面向过程的方式来编写相同功能的程序(还有函数式、声明式等,我们暂不深入)。Python的多范式依赖于Python对象中的特殊方法(special method)

特殊方法名的前后各有两个下划线。特殊方法又被成为魔法方法(magic method),定义了许多Python语法和表达方式,正如我们在下面的例子中将要看到的。当对象中定义了特殊方法的时候,Python也会对它们有“特殊优待”。比如定义了__init__()方法的类,会在创建对象的时候自动执行__init__()方法中的操作。

(可以通过dir()来查看对象所拥有的特殊方法,比如dir(1))

Python的运算符是通过调用对象的特殊方法实现的。比如:

‘abc’ + ‘xyz’               # 连接字符串

实际执行了如下操作:

‘abc’.__add__(‘xyz’)

len([1,2,3])      # 返回表中元素的总数

实际上做的是

[1,2,3].__len__() 

相对与__len__(),内置函数len()也起到了简化书写的作用。

尝试下面的操作,想一下它的对应内置函数

(-1).__abs__()

(2.3).__int__()

li = [1, 2, 3, 4, 5, 6]

print(li[3])

上面的程序运行到li[3]的时候,Python发现并理解[]符号,然后调用__getitem__()方法。

li = [1, 2, 3, 4, 5, 6]

print(li.__getitem__(3))

尝试看下面的操作,想想它的对应

li.__setitem__(3, 0)

{‘a’:1, ‘b’:2}.__delitem__(‘a’)

我们已经说过,在Python中,函数也是一种对象。实际上,任何一个有__call__()特殊方法的对象都被当作是函数。比如下面的例子:

class SampleMore(object):

    def __call__(self, a):

        return a + 5

add = SampleMore()     # A function object

print(add(2))          # Call function    

map(add, [2, 4, 5])    # Pass around function object

Python 魔术方法指南 — PyCoder’s Weelky CN

__new__(cls, […)

__init__(self, […)

__del__(self)

__eq__(self, other) 定义了等号的行为, == 。

__ne__(self, other) 定义了不等号的行为, != 。

__lt__(self, other) 定义了小于号的行为, < 。

__gt__(self, other) 定义了大于等于号的行为, >= 。

__pos__(self) 实现正号的特性(比如 +some_object)

__neg__(self) 实现负号的特性(比如 -some_object)

__abs__(self) 实现内置 abs() 函数的特性。

__invert__(self) 实现 ~ 符号的特性。

_add__(self, other) 实现加法。

__sub__(self, other) 实现减法。

__mul__(self, other) 实现乘法。

__floordiv__(self,other) 实现 // 符号实现的整数除法。

__div__(self, other) 实现 / 符号实现的除法。

__truediv__(self, other) 实现真除法。 注意只有只用了 from __future__ import division 的时候才会起作用。

__mod__(self, other) 实现取模算法 %

__divmod___(self, other) 实现内置 divmod() 算法

__pow__ 实现使用 ** 的指数运算

__lshift__(self, other) 实现使用 << 的按位左移动

__rshift__(self, other) 实现使用 >> 的按位左移动

__and__(self, other) 实现使用 & 的按位与

__or__(self, other)实现使用 | 的按位或

__xor__(self, other) 实现使用 ^ 的按位异或

魔术方法
调用方式
解释
__new__(cls [,…])
instance = MyClass(arg1, arg2)
__new__ 在创建实例的时候被调用
__init__(self [,…])
instance = MyClass(arg1, arg2)
__init__ 在创建实例的时候被调用
__cmp__(self, other)
self == other, self > other, 等。
在比较的时候调用
__pos__(self)
+self
一元加运算符
__neg__(self)
-self
一元减运算符
__invert__(self)
~self
取反运算符
__index__(self)
x[self]
对象被作为索引使用的时候
__nonzero__(self)
bool(self)
对象的布尔值
__getattr__(self, name)
self.name # name 不存在
访问一个不存在的属性时
__setattr__(self, name, val)
self.name = val
对一个属性赋值时
__delattr__(self, name)
删除一个属性时
__getattribute(self, name)
访问任何属性时
__getitem__(self, key)
self[key]
使用索引访问元素时
__setitem__(self, key, val)
self[key] = val
对某个索引值赋值时
__delitem__(self, key)
del self[key]
删除某个索引值时
__iter__(self)
for x in self
迭代时
__contains__(self, value)
value in self, value not in self
使用 in 操作测试关系时
__concat__(self, value)
self + other
连接两个对象时
__call__(self [,…])
self(args)
“调用”对象时
__enter__(self)
with self as x:
with 语句环境管理
__exit__(self, exc, val, trace)
with self as x:
with 语句环境管理
__getstate__(self)
pickle.dump(pkl_file, self)
序列化
__setstate__(self)
data = pickle.load(pkl_file)
序列化

转载请注明:在路上 » 【整理】Python 特殊方法 魔术方法

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
94 queries in 0.223 seconds, using 23.37MB memory