【问题标题】:invoking a class method inside the class itself在类本身内部调用类方法
【发布时间】: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 中收到 variable1variable2 的值,您还可以在 __init__ 方法中创建一个 self.summation 变量并在其他类方法中使用它。
  • 在您的 __sum 方法中,您将某些内容分配给 self.summation - 但该方法中没有 self。你期望这个方法做什么? summation 应该是类变量吗?
  • 对方法名称使用双前导下划线可能会由于 Python 名称修饰而在将来的属性访问中导致一些问题,除非这是您的意图。大多数时候,单个前导下划线用于“内部”方法/属性
  • @Aran-Fey 我忘了把 self 放在我现在编辑并修复它的方法中
  • @N Chauhan 是的,我知道这个

标签: python class methods


【解决方案1】:

这样的东西似乎正是您要找的东西:

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())。

【讨论】:

  • variable_1 也是在用户使用其中一种方法后计算的,所以我需要在用户使用某些方法后调用 __sum 函数并输入计算值
  • 看看编辑;可能有帮助。老实说,我很难理解您到底在寻找什么。
  • 请检查 cmets 提出的问题以了解我的目的
  • 对不起,我猜这可能是因为语言障碍,但我认为还没有人清楚您的要求。看看这个;也许您想从类内部调用一个类方法,而不是从另一个类方法中调用? stackoverflow.com/questions/13900515/…
【解决方案2】:

假设您在实例化类时会收到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)

【讨论】:

    猜你喜欢
    • 2014-07-18
    • 2018-10-08
    • 2019-04-16
    • 2015-06-19
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 2023-03-23
    • 2012-02-21
    相关资源
    最近更新 更多