关于python:在类本身内部调用类方法

invoking a class method inside the class itself

大家好,我想对类方法的其余部分使用类本身的方法的计算值,但它必须全部计算一次,我需要在类本身内部调用方法,我编写了一个示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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)


假设在实例化第一类解决方案时,您将收到variable1variable2,可以是:

1
2
3
4
5
6
class something():
    def __init__(self, variable1, variable2):
        self.summation = variable1 + variable2

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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)

像这样的东西似乎是你想要的:

1
2
3
4
5
6
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 = Something(),则可以随时使用self.method_name()调用该类方法。