Python魔法方法

前言

顾名思义,魔法方法是指一种带有特殊功能的方法。

常用魔法方法

魔法方法有很多,在此主要介绍一下些常用魔法方法

1、new()

该方法是通过类创建实例所调用的第一个魔法方法。只有新式类才有魔法方法__new__(),而从Object类继承的子类,都是新式类。
Object类关于这个方法的定义如下:

Static methods defined here:
 |
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.

如何使用:


class A(object):
    def __init__(self, value):
        print  "use __init__"
        self.value = value
    def __new__(cls, *args, **kwargs):
        print "use __new__"
        return super(A, cls).__new__(cls, *args, **kwargs)
 
a =  A(555)
 
# 结果如下:
# ues __new__
# ues __init__

可发现,在调用__init__()初始化前,先调用了__new__()。
它的作用:
__new__方法主要是当你继承一些不可变的class时(比如int, str, tuple), 提供给你一个自定义这些类的实例化过程的途径。

假如我们需要一个永远都是正数的整数类型。

class PositiveInteger(int):
    def __init__(self, value):
        super(PositiveInteger, self).__init__(self, abs(value))
 
 
i = PositiveInteger(-3)
print i
 
# -3
 
class PositiveInteger(int):
    def __new__(cls, value):
        return super(PositiveInteger, cls).__new__(cls, abs(value))
 
 
i = PositiveInteger(-3)
print i
 
# 3

2、__init__魔法方法

事实上python通过类创建实例时首先通过__new__创造实例,而__init__只是将传入的参数来初始化该实例。因此self代表该实例本身。__new__魔法和__init__魔法共同组成了类似其他语言的"构造函数"。通俗讲,__new__创造实例,__init__初始化实例。

3、__del__魔法

__del__可以理解为析构函数

4、 运算符相关的魔法方法

运算符相关的魔法方法实在太多了,也很好理解,不打算多讲。在其他语言里,也有重载运算符的操作,所以我们对这些魔法方法已经很了解了。
eq(self, other)

定义了比较操作符==的行为.

ne(self, other)

定义了比较操作符!=的行为.

lt(self, other)

定义了比较操作符<的行为.

gt(self, other)

定义了比较操作符>的行为.

le(self, other)

定义了比较操作符<=的行为.

ge(self, other)

定义了比较操作符>=的行为.
pos(self)

实现了’+'号一元运算符(比如+some_object)

neg(self)

实现了’-'号一元运算符(比如-some_object)

invert(self)

实现了号(波浪号)一元运算符(比如some_object)

abs(self)

实现了abs()內建函数.

round(self, n)

实现了round()内建函数. 参数n表示四舍五进的精度.

floor(self)

实现了math.floor(), 向下取整.

ceil(self)

实现了math.ceil(), 向上取整.

trunc(self)

实现了math.trunc(), 向0取整.
add(self, other)

实现了加号运算.

sub(self, other)

实现了减号运算.

mul(self, other)

实现了乘法运算.

floordiv(self, other)

实现了//运算符.

div(self, other)

实现了/运算符. 该方法在Python3中废弃. 原因是Python3中,division默认就是true division.

truediv(self, other)

实现了true division. 只有你声明了from future import division该方法才会生效.

mod(self, other)

实现了%运算符, 取余运算.

divmod(self, other)

实现了divmod()內建函数.

pow(self, other)

实现了**操作. N次方操作.

lshift(self, other)

实现了位操作<<.

rshift(self, other)

实现了位操作>>.

and(self, other)

实现了位操作&.

or(self, other)

实现了位操作|

xor(self, other)

实现了位操作^

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值