python魔术方法abstract_Python 进阶之魔术方法

Python魔术方法

__开头,__结尾的方法就是魔术方法.

1.__str__格式化输出对象

__repr__表示对象本身

class A:

def __str__(self):

return 'This is A'

# 表示对象本身

def __repr__(self):

return "I'm a A"

a = A()

print(a) # This is A

a # I'm a A

2.__init__和 __new__

__init__ 初始化实例,无返回值

__new__创建一个实例,并返回类的实例.

__new__是一个特殊的类方法,不需要使用@classmethod来装饰.

使用__new__单例模式

# 借助__new__方法实现单例模式

class Singleton:

instance = None

def __new__(cls, *args, **kwargs):

# 判断实例对象是否已经存在

if cls.instance is None:

# 说明实例对象不存在.需要创建

cls.instance = super().__new__(Singleton, *args, **kwargs)

return cls.instance

s = Singleton()

s2 = Singleton()

s is s2

out: True

display(id(s), id(s2))

out: 78960288 78960288

3.数学运算、比较运算

运算符重载

+:__add__(value)

-: __sub__(value) substract

*: __mul__(value) mulply

/: __truediv__(value) (Python 3.x), __div__(value) (Python 2.x) divide

//: __floordiv__(value)

%: __mod__(value)

&: __and__(value)

|:__or__(value)

# 自定义字典的加法

class Dict(dict):

# 实现加法

def __add__(self, other):

# 判断other是否是字典.

if isinstance(other, dict):

new_dict = {}

new_dict.update(self)

new_dict.update(other)

return new_dict

else:

raise TypeError('not a dict')

d1 = {1: 11, 2: 22}

d2 = {1: 111, 2: 222, 3:333}

dd1 = Dict(d1)

dd1 + d2

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值