在Python中,类的函数(包括实例方法和类方法)的调用方式如下:
一、实例方法调用
-
定义方式
实例方法以
self
为第一个参数,用于访问实例属性。例如:class Dog: def __init__(self, name): self.name = name def bark(self): print(f"{self.name} is barking!")
-
调用方式
通过实例对象调用,使用点号
.
操作符。例如:my_dog = Dog("Buddy") my_dog.bark() # 输出: Buddy is barking!
二、类方法调用
-
定义方式
类方法使用
@classmethod
装饰器,第一个参数为cls
(类本身)。例如:class Rectangle: def __init__(self, width, height): self.width = width self.height = height @classmethod def area(cls, width, height): return cls.width * cls.height
-
调用方式
-
通过类名直接调用:
Rectangle.area(3, 4) # 输出: 12
-
通过实例对象调用:
rect = Rectangle(3, 4) rect.area(3, 4) # 输出: 12
-
三、注意事项
-
参数传递 :实例方法通过
self
访问实例属性,类方法通过cls
访问类属性或创建类实例。 -
默认参数 :类方法可设置默认参数,例如:
class Greeter: def greet(self, name="Guest"): print(f"Hello, {name}!") greeter = Greeter() greeter.greet() # 输出: Hello, Guest! greeter.greet("Alice") # 输出: Hello, Alice!
-
调用顺序 :类方法调用时,
self
和cls
参数无需显式传递,Python自动处理。
以上是Python中类函数调用的核心方法,结合实例与类方法的使用场景,可满足不同需求。