在类本身内部调用类方法

时间:2018-08-15 11:08:52

标签: python class methods

大家好,我想使用来自类本身方法的计算所得的值作为其余类方法的方法,但它必须全部计算一次,我需要在类本身内部调用方法,我写一个例子:

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)

2 个答案:

答案 0 :(得分:0)

您正在寻找这样的东西

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()(如果在外部使用(instance = Something()))。

答案 1 :(得分:0)

假设在实例化类时,您将收到variable1variable2,可能是:

class something():
    def __init__(self, variable1, variable2):
        self.summation = variable1 + variable2

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

如果相反,您正在其他方法中创建variable1variable2,则可以使它们成为类变量:

class Something():
    def __init__(self):
        #Put some initialization code here

    def some_other_method(self):
        self.variable1 = something
        self.variable2 = something

    def sum(self):
        try:
            self.summation = self.variable1 + self.variable2
        except:
            #Catch your exception here, for example in case some_other_method was not called yet

    def do_something_with_summation(self):
        print(self.summation)
相关问题