【发布时间】:2018-08-15 11:08:52
【问题描述】:
大家好,我想为其余的类方法使用类本身方法的计算值,但它必须计算一次,我需要在类本身中调用方法我写了一个例子:
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)
【问题讨论】:
-
正确的语法应该是
self.__sum(1, 2)。如果您在 init 中收到variable1和variable2的值,您还可以在__init__方法中创建一个self.summation变量并在其他类方法中使用它。 -
在您的
__sum方法中,您将某些内容分配给self.summation- 但该方法中没有self。你期望这个方法做什么?summation应该是类变量吗? -
对方法名称使用双前导下划线可能会由于 Python 名称修饰而在将来的属性访问中导致一些问题,除非这是您的意图。大多数时候,单个前导下划线用于“内部”方法/属性
-
@Aran-Fey 我忘了把 self 放在我现在编辑并修复它的方法中
-
@N Chauhan 是的,我知道这个