Skip to main content
 首页 » 编程设计

python之为类分配两个函数

2025年05月04日14artech

class Math: 
 
    def __init__(self, number): 
        self.number = number 
 
    def add(self, add_num): 
        return self.number + add_num 
 
    def sub(self, sub_num): 
        return self.number - sub_num 

数学(5).add(5)

我按预期得到了 10

但如果我执行 Math(5).add(5).sub(3): 我收到此错误 AttributeError: 'int' object has no attribute 'sub'

请您参考如下方法:

要使其正常工作,您的方法需要返回 self(或 Math 的新实例):

class Math: 
 
    def __init__(self, number): 
        self.number = number 
 
    def add(self, add_num): 
        self.number += add_num 
        return self 
        # or: 
        # return Math(self.number + add_num) 
 
    def sub(self, sub_num): 
        self.number -= sub_num 
        return self 
        # or: 
        # return Math(self.number - add_num) 
 
    def __str__(self): 
        return str(self.number) 
 
m = Math(5).add(5).sub(3) 
print(m) 
# 7 

add 现在的行为更像 __iadd__ .