Python---__add__(self, other)“实例方法”和“特殊方法”的初学
“语法糖” --简化写法
s1 = a
s2 = b
print(s1 + s2)
结果:ab
如果直接调用实例方法
将s1+s2,简化成s1.__add__(s2)
结果:ab
__add__(self,other)中self和other的含义
self = 调用__add__的那个对象(比如s1.__add__(s2)中,self就是s1);other = 要和self做 “加法” 的另一个对象(比如s1.__add__(s2)中,other就是s2);
以下代码是ai帮助产生的。
我疑惑,它的运行方式
class MyNum:
def __init__(self, value):
self.value = value # self绑定实例的value
def __add__(self, other):
# self = 调用者(比如n1),other = 传入的参数(比如n2)
print(f"self是:{self.value},other是:{other.value}")
return MyNum(self.value + other.value)
# 实例化
n1 = MyNum(10)
n2 = MyNum(20)
# 调用__add__
result = n1 + n2 # 等价于n1.__add__(n2)
print(result.value) # 输出30
# 控制台还会打印:self是:10,other是:20 → 清晰看到self和other的指向
问题就是在return MyNum(self.value + other.value),如果改成return self.value + other.value
太跳跃了,真的没法理解这个问题。
这种模式让我的思维跟不上趟。
我们来修改一下
一个类只能对应一个实例干活
class MyNum:
def __init__(self,value):
self.value = value
print(MyNum())
TypeError:MyNum.__init__() missing 1 required positional argument:'value'

class MyNum:
def __init__(self,value):
self.value = value
def __add__(self,value):
return MyNum(self.value)
print(MyNum(20))
没有出错但打印类型??
<main.MyNum object at 0x10eac7380>

不断的换打印条件
class MyNum:
def __init__(self, value):
self.value = value # self绑定实例的value
def __add__(self, other):
return MyNum(self,other)
n1 = MyNum(10)
n2 = MyNum(20)
print(n1+n2)

class MyNum:
def __init__(self, value):
self.value = value # self绑定实例的value
def __add__(self, other):
return MyNum(self)
n1 = MyNum(10)
n2 = MyNum(20)
print(n1)

“魔法”下划线的魔法
我才想到一个问题,在第7章我学到类概念中 def getNum(self): def setNum(self):
而AI给我的是def__add__(self, other),这个下划线是不是有什么不可告人的秘密呢?不对是我还不知道的东西呢??1
用__add__来写类,
class MyNum:
def __init__(self, value):
self.value = value # self绑定实例的value
def __add__(self, other):
# self = 调用者(比如n1),other = 传入的参数(比如n2)
print(f"self是:{self.value},other是:{other.value}")
return MyNum(self.value + other.value)
n1 = MyNum(10)
n2 = MyNum(20)
result = n1 + n2
print(result.value)
那接下来让我用我学的第7章类的知识也来做一个带有__add__功能的函数吧
初次尝试和各种错误
TypeError:MyNum.getAdd() missing 1 required required positional argument: 'other2'
class MyNum:
def __init__(self, other1,other2):
self.other1 = other1 # self绑定实例的value
self.other2 = other2 # self绑定实例的value
def getAdd(self,other1,other2):
return self.other1 + self.other2
n1 = MyNum.getAdd(10,20)
print(n1)

def getAdd(self,):
return self +self.other

最后代码
class MyNum:
def __init__(self, value):
self.value = value # self绑定实例的value
def getAdd(self, other):
return self.value + other
num1= 10
num2= 20
n1 = MyNum(num1)
print(f"没用魔法,直接用原始的逻辑完成的结果{num1} + {num2} =",n1.getAdd(num2))

-
以双下划线开头 / 结尾(或仅双下划线包裹)的方法 / 属性被称为「魔法方法(Magic Methods)」或「特殊方法(Special Methods)」,也常被称作 “dunder 方法”(dunder = double underscore)。它们不是 Python 开发者随意命名的,而是 Python 解释器内置的、有特殊语义的标识符 —— 核心作用是让自定义对象支持 Python 的原生语法 / 操作,比如加减乘除、循环、索引、比较等,无需手动调用,由解释器自动触发。 ↩︎
更多推荐



所有评论(0)