首页 > 解决方案 > 在类本身内部调用类方法

问题描述

大家好,我想将类本身的方法的计算值用于其余的类方法,但它必须一劳永逸地计算,我需要在类本身内部调用方法我写了一个例子:

class something():
    def __init__():
        pass

    def __sum(self, variable_1, variable_2):
        self.summation = sum(variable_1, variable_2)

    # I need to calculate summation here once for all:
    # how does the syntax look likes, which one of these are correct:

    something.__sum(1, 2)
    self.__sum(1, 2)

    # If none of these are correct so what the correct form is?
    # For example print calculated value here in this method:

    def do_something_with_summation(self):
        print(self.summation)

标签: pythonclassmethods

解决方案


像这样的东西似乎是你正在寻找的东西:

class Something:
    def __init__(self):
        self.__sum(1, 2)

    def __sum(self, variable_1, variable_2):
        self.summation = sum(variable_1, variable_2)

并不是说这是理想的方法或任何东西,但你并没有真正给我们太多的东西。

一般来说,确保self是所有类方法中的第一个参数,并且您可以随时调用该类方法,无论self.method_name()是在另一个类方法中instance.method_name()使用它还是在外部使用它(where instance = Something())。


推荐阅读