简体   繁体   English

在同一个 class 中调用方法及其依赖项,得到 Python 中的期望值

[英]Call a method and its dependencies within the same class to get the expected value in Python

I'm trying to simplify my code to increase productivity and avoid typing errors and Object Oriented Programming (OOP) seems the way to follow.我正在尝试简化我的代码以提高生产力并避免输入错误,而 Object 面向编程 (OOP) 似乎是要遵循的方法。 I'm new to OOP and have started to learn about classes and methods in Python.我是 OOP 的新手,并且已经开始了解 Python 中的类和方法。 I'm working in a personal project involving consecutive steps to get a final result in which every step depends on the results of previous steps but intermediate results are also useful on its own.我正在从事一个涉及连续步骤以获得最终结果的个人项目,其中每个步骤都取决于先前步骤的结果,但中间结果本身也很有用。

Let's start with the definition of the class:让我们从 class 的定义开始:

class MyClass():

def __init__(self, data):
    self.var_1 = data[0]
    self.var_2 = data[1]
    self.var_3 = data[2]
    
def method_1(self):
    self.result_1 = self.var_1 + self.var_2
    return self.result_1

def method_2(self):
    self.result_2 = self.var_3 * self.result_1
    return self.result_2

Next I create the object:接下来我创建 object:

food = [7, 15, 32]
A = MyClass(food)
print(A.method_2)

The result:结果:

<bound method MyClass.method_2 of <__main__.MyClass object at 0x00000249A2C54C48>> instead of the desired 704

I have done my homework and tried several solutions:我已经完成了作业并尝试了几种解决方案:

  1. First : call every method needed to get result prior to call the desired.首先:在调用所需的方法之前调用获得结果所需的每个方法。

    B = MyClass(food) B.method_1() print(B.method_2())

Result:704结果:704

  1. Second : put the calls in init to force to evaluate them every time I instantiate the object.第二:每次实例化 object 时,将调用放入init以强制评估它们。 Discovered here: Enforce a sequence for calling methods in a class在这里发现: 在 class 中执行调用方法的顺序

    class MyClass(): class MyClass():

     def __init__(self, data): self.var_1 = data[0] self.var_2 = data[1] self.var_3 = data[2] MyClass.method_1(self) MyClass.method_2(self) def method_1(self): self.result_1 = self.var_1 + self.var_2 return self.result_1 def method_2(self): self.result_2 = self.var_3 * self.result_1 return self.result_2

Creating and calling gives 704:创建和调用给出 704:

C= MyClass(food)
print(C.method_2())

This can be modified using a idea from this thread: Run all functions in class这可以使用该线程的一个想法进行修改: Run all functions in class

Defining a new method within the class:在 class 中定义新方法:

def method_all(self):
        MyClass.method_1(self)
        MyClass.method_2(self)

Calling before does the trick先打电话就行了

E = MyClass(food)
E.method_all()
print(E.method_2())

Is there a preferred method?有首选方法吗? Another solution that forces to evaluate needed methods before the desired one?另一种强制在所需方法之前评估所需方法的解决方案?

Here is one way using hasattr :这是使用hasattr的一种方法:

def method_2(self):
    if not hasattr(self, 'result_1'):
        self.method_1()
    self.result_2 = self.var_3 * self.result_1

Regarding your class itself and the way you first tried to print the results: you called a method the way an attribute is called, that is, without parenthesis (in your print statement).关于您的 class 本身以及您首次尝试打印结果的方式:您以调用属性的方式调用方法,即没有括号(在您的打印语句中)。 Second, you should call method_1 to define result_1 before using it (even if it has "self", it's not automatically defined).其次,你应该在使用它之前调用method_1来定义result_1(即使它有“self”,它也不会自动定义)。 By the way, you do not need to repeat "self" when you return the variable at the end of the method.顺便说一句,在方法结束时返回变量时不需要重复“self”。

So trying to stay as close to your original code (the simplest), this is a working solution:因此,尝试尽可能接近原始代码(最简单),这是一个可行的解决方案:

class MyClass():
    def __init__(self, data):
        self.var_1 = data[0]
        self.var_2 = data[1]
        self.var_3 = data[2]

    def method_1(self):
        result_1 = self.var_1 + self.var_2
        return result_1

    def method_2(self):
        result_1 = self.method_1()
        result_2 = self.var_3 * result_1
        return result_2


food = [7, 15, 32]
A = MyClass(food)
print(A.method_2())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM