Python – Math Operatives (Class, Functions) 如何创建一个带有函数并结合数学的类

huangapple go评论92阅读模式
英文:

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,

  1. class Math:
  2. def add(self, x, y):
  3. return(x + y)
  4. def subtract(self, x, y):
  5. return(x - y)
  6. def multiply(self, x, y):
  7. return(x * y)
  8. def divide(self, x, y):
  9. return(x / y)
  10. print(divide(5, 5))

答案1

得分: 1

因为您在Math类定义下定义了这些函数,所以您需要创建一个Math类的实例来调用这些函数。

  1. math_obj = Math()
  2. print(math_obj.divide(5, 5))

如果您希望这个示例在类被实例化时立即运行,您需要定义一个__init__函数,该函数在创建该类的对象时运行。请注意,该函数仍然与类相关联,因此在类内部,您要使用self变量。

  1. class Math:
  2. def __init__(self):
  3. print(self.divide(5, 5))
  4. def add(self, x, y):
  5. return(x + y)
  6. def subtract(self, x, y):
  7. return(x - y)
  8. def multiply (self, x, y):
  9. return(x * y)
  10. def divide (self, x, y):
  11. 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.

  1. math_obj = Math()
  2. 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.

  1. class Math:
  2. def __init__(self):
  3. print(self.divide(5, 5))
  4. def add(self, x, y):
  5. return(x + y)
  6. def subtract(self, x, y):
  7. return(x - y)
  8. def multiply (self, x, y):
  9. return(x * y)
  10. def divide (self, x, y):
  11. return(x / y)

huangapple
  • 本文由 发表于 2023年2月7日 01:31:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/75364665.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定