python - 为类分配两个函数?

标签 python function class

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__ .

关于python - 为类分配两个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55470013/

相关文章:

python - SQLAlchemy 子字符串在字符串中

mysql - where 子句中小写

c++ - 为什么这个 "boost::bind"不能编译?

android - 如何使用 Mockito 2 在 java/android 测试下模拟最终类?

python - 如何克服数据 "TypeError: list indices must be integers or slices, not str"中的pa中的["result"]

python - 为类和静态方法配置lru_cache

python - python 如何在任务栏弹出最小化程序

python - matplotlib 中的条件函数绘图

c++ - 变量可以调用私有(private)函数吗?

c++ - 如何将继承类拆分为不同的 .h/.cpp 文件?