首页 > 解决方案 > 使用类 python 组织类似的方法

问题描述

我只是想知道如何将 python 类中的类似方法分组。这是一个例子:

class Test:
def add(a, b):
    return a + b
def sub(a, b):
    return a - b

我想对这些函数进行分组,以便您可以这样称呼它们

me = Test
print(me.math.add(5, 2))
print(me.math.sub(5, 2))

如果这是可能的。在这种情况下,我将这些函数与称为数学的东西组合在一起。我什至不确定你是否可以这样做,但它会很方便

标签: pythonclassmethods

解决方案


这行得通吗?

class Test:
    def __init__(self):
        self.math = Math()

class Math:
    def add(self, a, b):
        return a + b
    def sub(self, a, b):
        return a - b

test = Test()
print(test.math.add(1, 3))
print(test.math.sub(6, 3))

推荐阅读