python - 在类本身内部调用类方法
问题描述
大家好,我想将类本身的方法的计算值用于其余的类方法,但它必须一劳永逸地计算,我需要在类本身内部调用方法我写了一个例子:
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)
解决方案
像这样的东西似乎是你正在寻找的东西:
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()
)。
推荐阅读
- python - Selenium 从具有相同类的多个下拉列表中选择 - 问题 python
- c# - 将 Sql 语句转换为 Entity Framework Core
- jpa - SQL LEFT JOIN AND JPA / HQL 查询
- python - Python请求库不检索内部元素“反应”类的标签
- vba - Excel VBA For 循环在一半的电子邮件被移动到另一个文件夹后停止
- java - 将目录中的所有文件复制到另一个目录不起作用
- dataframe - 如何根据atoti中的现有变量创建存储桶?
- json - 使用 Aurelia 在前端将动态嵌套 JSON 显示为 Treeview
- python-behave - Python Behave钩子未被调用
- axios - 如何在世博会应用程序中使用 cookie 进行身份验证