魔法方法总是被双下划线包围 魔法方法的“魔力”体现在它们总能够在适当的时候被自动调用。 魔法方法的第一个参数应为
cls
(类方法)
或者self
(实例方法)。
cls
:代表一个类的名称self
:代表一个实例对象的名称
__init__(self[, ...])
与__new__(cls[, ...])
__new__
是在一个对象实例化的时候所调用的第一个方法,在调用__init__
初始化前,先调用__new__
__new__
至少要有一个参数cls
,代表要实例化的类,此参数在实例化时由 Python 解释器自动提供,后面的参数直接传递给__init__
。
__new__
对当前类进行了实例化,并将实例返回,传给__init__
的self。但是,执行了__new__
,并不一定会进入__init__
,只有__new__
返回了,当前类cls的实例,当前类的__init__
才会进入若
__new__
没有正确返回当前类cls的实例,那__init__
是不会被调用的,即使是父类的实例也不行,将没有__init__
被调用。
__init__(self[, ...])
与__new__(cls[, ...])
的传递关系:
__new__(cls[, ...])
需要设置有返回值,而__init__(self[, ...])
可以不设置返回值。
该返回值决定了
- 实例化对象的初始化(赋值)
- 之后是否进入
__new__(cls[, ...])
方法
class A(object):
def __init__(self, value):
print("into A __init__")
self.value = value
def __new__(cls, *args, **kwargs):
print("into A __new__")
print(cls)
return object.__new__(cls)
class B(A):
def __init__(self, value):
print("into B __init__")
self.value = value
def __new__(cls, *args, **kwargs):
print("into B __new__")
print(cls)
return super().__new__(cls, *args, **kwargs)
b = B(10)
# 结果:
# into B __new__
# <class '__main__.B'>
# into A __new__
# <class '__main__.B'>
# into B __init__
class A(object):
def __init__(self, value):
print("into A __init__")
self.value = value
def __new__(cls, *args, **kwargs):
print("into A __new__")
print(cls)
return object.__new__(cls)
class B(A):
def __init__(self, value):
print("into B __init__")
self.value = value
def __new__(cls, *args, **kwargs):
print("into B __new__")
print(cls)
return super().__new__(A, *args, **kwargs) # 改动了cls变为A
b = B(10)
# 结果:
# into B __new__
# <class '__main__.B'>
# into A __new__
# <class '__main__.A'>
————————————————
版权声明:本文为CSDN博主「老马的程序人生」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/LSGO_MYP/article/details/102887712
单例模式:
此处将类的私有属性赋值cls
实例object.__new__(cls)
再返回该值作为实例化的最终对a
,b
的赋值,并且不会进入__init__(self[, ...])
class Earth:
pass
a = Earth()
print(id(a)) # 260728291456
b = Earth()
print(id(b)) # 260728291624
class Earth:
__instance = None # 定义一个类属性做判断
def __new__(cls):
if cls.__instance is None:
cls.__instance = object.__new__(cls)
return cls.__instance
else:
return cls.__instance
a = Earth()
print(id(a)) # 512320401648
b = Earth()
print(id(b)) # 512320401648
————————————————
版权声明:本文为CSDN博主「老马的程序人生」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/LSGO_MYP/article/details/102887712
__new__
方法主要是当你继承一些不可变的class
时(比如int
,str
,tuple
),提供给你一个自定义这些类的实例化过程的途径。
此处将str
类进行改写
class CapStr(str):
def __new__(cls, string):
string = string.upper()
return str.__new__(cls, string)
a = CapStr("i love lsgogroup")
print(a) # I LOVE LSGOGROUP
————————————————
版权声明:本文为CSDN博主「老马的程序人生」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/LSGO_MYP/article/details/102887712
__del__(self)
析构器,当一个对象将要被系统回收之时调用的方法。
即对象用del
关键字消除时自动调用的方法
__str__(self)
- 当你打印一个对象的时候,触发
__str__
- 当你使用%s格式化的时候,触发
__str__
- str强转数据类型的时候,触发
__str__
__repr__(self)
- repr是str的备胎
- 有__str__的时候执行__str__,没有实现__str__的时候,执行__repr__
- repr(obj)内置函数对应的结果是__repr__的返回值
- 当你使用%r格式化的时候 触发__repr__
__str__(self)
的返回结果可读性强。也就是说,__str__
的意义是得到便于人们阅读的信息,就像下面的
‘2019-10-11’ 一样。
__repr__(self)
的返回结果应更准确。怎么说,__repr__
存在的目的在于调试,便于开发者使用。
import datetime
today = datetime.date.today()
print(str(today)) # 2019-10-11
print(repr(today)) # datetime.date(2019, 10, 11)
print('%s' %today) # 2019-10-11
print('%r' %today) # datetime.date(2019, 10, 11)
————————————————
版权声明:本文为CSDN博主「老马的程序人生」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/LSGO_MYP/article/details/102887712
算术运算符与反算术运算符
区别:
a + b
这里加数是a
,被加数是b
,因此是a
主动,反运算就是如果a
对象的__add__()
方法没有实现或者不支持相应的操作,那么 Python 就会调用b
的__radd__()
方法。
class Nint(int):
def __radd__(self, other):
return int.__sub__(other, self) # 注意 self 在后面
a = Nint(5)
b = Nint(3)
print(a + b) # 8
print(1 + b) # -2