英文:
Python - Math Operatives (Class, Functions) How to create a class with functions and incorporate Math
问题
class Math:
def add(self, x, y):
return(x + y)
def subtract(self, x, y):
return(x - y)
def multiply(self, x, y):
return(x * y)
def divide(self, x, y):
return(x / y)
print(Math().divide(5, 5))
英文:
I wanted to create a class with a specific user defined function for each math operative and then print an example with results. I am obviously missing something here and was hoping someone could provide some insight. Thank you,
class Math:
def add(self, x, y):
return(x + y)
def subtract(self, x, y):
return(x - y)
def multiply(self, x, y):
return(x * y)
def divide(self, x, y):
return(x / y)
print(divide(5, 5))
答案1
得分: 1
因为您在Math
类定义下定义了这些函数,所以您需要创建一个Math
类的实例来调用这些函数。
math_obj = Math()
print(math_obj.divide(5, 5))
如果您希望这个示例在类被实例化时立即运行,您需要定义一个__init__
函数,该函数在创建该类的对象时运行。请注意,该函数仍然与类相关联,因此在类内部,您要使用self
变量。
class Math:
def __init__(self):
print(self.divide(5, 5))
def add(self, x, y):
return(x + y)
def subtract(self, x, y):
return(x - y)
def multiply (self, x, y):
return(x * y)
def divide (self, x, y):
return(x / y)
希望这些翻译对您有帮助。
英文:
Because you've defined these functions under your class definition of Math
, you need an instance of the Math
class in order to call these functions.
math_obj = Math()
print(math_obj.divide(5, 5))
If you want that example to run as soon as the class is instantiated, you need to define an __init__
function, which runs whenever an object of that class is created. Note that the function is still attached to the class, so within a class, you use the self
variable.
class Math:
def __init__(self):
print(self.divide(5, 5))
def add(self, x, y):
return(x + y)
def subtract(self, x, y):
return(x - y)
def multiply (self, x, y):
return(x * y)
def divide (self, x, y):
return(x / y)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论