问题:你想了解如何在类中定义 Python 方法。
解决方案:
方法定义:
定义一个类: 首先使用 class 关键字定义一个类。
class Calculator:
def add(self, x, y):
return × + V
def subtract(self, x, y):
return x - y
定义和访问方法: 在类定义中,将方法定义为函数。要访问方法,可创建类的实例,并使用点符号在这些实例上调用方法。
# Creating an instance of the Calculator class
calculator = Calculator()
# Calling methods on the instance
result1 = calculator.add(5, 3) # Calls the 'add' method
result2 = calculator.subtract (10, 4) # Calls the 'subtract' method
方法参数: 方法可以接受自参数以外的参数。
class Rectangle:
def area(self, width, height):
return width * height
# Creating an instance of the Rectangle class
rect = Rectangle()
# Calling the 'area' method with parameters
area = rect.area(4, 6)