如何使用 3 个函数调用 class?

How to call on a class using 3 functions?

我想创建一个具有 3 个功能的 Python class。

这是我目前的代码:

class Product:

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def get_x(self):
        x = int(input('What is the first number?: ')

    def get_y(self):
        y = int(input('What is the second number?: ')

    def mult_XY(self):
        return x * y  

当我尝试调用 class 时,我得到 'y' is not defined

我尝试使用以下代码:

num = Product(x, y)
print(num.mult_XY)

您似乎忘记在函数定义中使用关键字 self。您的代码中有很多错误。 我认为这是您代码的正确版本:

class Product:

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def get_x(self):
        self.x = int(input('What is the first number?: '))

    def get_y(self):
        self.y = int(input('What is the second number?: '))

    def mult_XY(self):
        return self.x * self.y

这就是您应该如何检查它是否正常工作:

(更新版本)

x = 10
y = 5
num = Product(x, y)
num.get_x()
num.get_y()
print(num.mult_XY())

要引用存储在当前对象中的任何内容,您需要像在 init 函数中那样使用 self. 来最初保存值。

示例:

class Product:

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def get_x(self):
        self.x = int(input('What is the first number?: '))

    def get_y(self):
        self.y = int(input('What is the second number?: '))

    def mult_XY(self):
        return self.x * self.y  

我不确定我是否理解正确,但您可能需要“x”和“y”作为 class 中的输入。

如果是这样,使用classmethods:

class Product:
    @classmethod
    def get_x(self):
        self.x = int(input('What is the first number?: '))
        return self
    @classmethod
    def get_y(self):
        self.y = int(input('What is the second number?: '))
        return self
    @classmethod
    def mult_XY(self):
        return self.x * self.y

例如:

>>> Product.get_x().get_y().mult_XY()
What is the first number?: 3
What is the second number?: 4
12
>>> 

这是一个可行的解决方案。将其与您当前的解决方案进行比较并找出差异。在下面的代码片段之后,我将突出显示您需要研究的概念,以便更好地理解该程序。

这是您的代码的正确版本(注意:可能有不止一种解决方案):

class Product:

    def __init__(self):
        return

    def get_x(self):
        self.x = int(input('What is the first number?: '))
        return self.x
    
    def get_y(self):
        self.y = int(input('What is the second number?: '))
        return self.y

    def mult_XY(self):
        return self.x * self.y

p = Product()
x = p.get_x()
y = p.get_y()
result = p.mult_XY()
print('RESULT of {} * {} = {}'.format(x, y, result))

这是最佳答案吗?不。根据您的程序的具体情况,代码的结构可能会有所不同。

您在以下概念上存在知识空白:

  • 对象和 类 在 Python
  • Python
  • 中的函数
  • Python
  • 中的变量和作用域

为了更好地理解,您需要了解更多Python的基础知识。这是一个很好的入门资源:https://python-textbok.readthedocs.io/en/1.0/Introduction.html

读完之后,您不仅可以回答这个问题,还可以为您的编程知识打下基础。不要放弃,祝你一切顺利。