Abl*_*her 7 python methods class
我想创建一个具有 3 个函数的 Python 类。
这是我到目前为止的代码:
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
Run Code Online (Sandbox Code Playgroud)
当我尝试打电话给班级时,我得到了'y' is not defined。
我尝试使用以下代码:
num = Product(x, y)
print(num.mult_XY)
Run Code Online (Sandbox Code Playgroud)
这是一个可行的解决方案。将其与您当前的解决方案进行比较并找出差异。在以下代码片段之后,我将重点介绍您需要研究的概念,以便更好地理解该程序。
这是代码的正确版本(注意:可能有不止一种解决方案):
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))
Run Code Online (Sandbox Code Playgroud)
这是最好的答案吗?不会。根据程序的具体情况,代码的结构可能会有所不同。
您对以下概念存在知识差距:
为了更好地理解,您需要更多地了解Python的基础知识。这里有一个很好的资源可以帮助您入门:https://python-textbok.readthedocs.io/en/1.0/Introduction.html
读完之后,你不仅能够回答这个问题,还能为你的编程知识打下基础。不要放弃并祝你一切顺利。