举一个例子 实例对象可以作为方法的入参

当一个实例对象作为类方法的参数时,我们可以将这个实例对象传递给另一个实例对象的方法,以实现不同实例对象之间的交互。以下是一个例子:

class Dog:
    def __init__(self, name):
        self.name = name
    
    def bark(self):
        print(self.name, "is barking!")
    
    def play_with(self, other_dog):
        print(self.name, "is playing with", other_dog.name)
        other_dog.bark()

# 创建两个 Dog 实例对象
dog1 = Dog("Buddy")
dog2 = Dog("Max")

# 调用 play_with 方法,将 dog2 作为参数传入
dog1.play_with(dog2)

在上面的例子中,类 Dog 中定义了两个方法:barkplay_withplay_with 方法接收另一个 Dog 类的实例对象作为参数,然后打印出两个狗狗一起玩耍的信息,并让另一个狗狗发出叫声。最后,通过实例对象 dog1 调用 play_with 方法,将 dog2 作为参数传入,输出 “Buddy is playing with Max” 和 “Max is barking!”。这样,实例对象 dog1dog2 就可以在方法调用中互相交互。