当一个实例对象作为类方法的参数时,通过这个实例对象可以访问其属性和方法,实现类方法对实例对象的操作。以下是一个简单的示例:
class Person:
def __init__(self, name):
self.name = name
def greet(self):
print("Hello, my name is", self.name)
@classmethod
def introduce(cls, person):
print("Let me introduce you to", person.name)
# 创建两个 Person 实例对象
person1 = Person("Alice")
person2 = Person("Bob")
# 调用类方法 introduce,将 person1 作为参数传入
Person.introduce(person1)
在上面的例子中,类 Person
中定义了两个方法:greet
和 introduce
。introduce
方法接收一个 Person
类的实例对象作为参数,然后打印出该实例对象的名字。最后,通过实例对象 person1
调用 introduce
方法,将 person1
作为参数传入,输出 “Let me introduce you to Alice”。