【发布时间】:2021-10-01 05:31:34
【问题描述】:
我想创建一个包含 3 个函数的 Python 类。
- 功能 1 将要求用户输入一个数字。
- 函数 2 将要求用户输入另一个数字。
- 函数 3 将函数 1 * 函数 2 相乘并返回乘积。
这是我目前的代码:
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
当我尝试调用课程时,我得到'y' is not defined。
我尝试使用以下代码:
num = Product(x, y)
print(num.mult_XY)
【问题讨论】:
-
使用这种方法,每个变量都需要
self.。 -
连括号,如果不关闭
int()语句,会抛出错误:y = int(input('What is the second number?: ')