在实例中如何调用init方法举个例子
在实例中调用init方法,需要先创建一个类的实例,然后通过该实例来调用init方法。以下是一个例子:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def say_hello(self):
print("Hello, my name is", self.name, "and I am", self.age, "years old.")
# 创建一个Person类的实例
person = Person("John", 25)
# 调用实例的init方法
person.__init__("Alice", 30)
# 调用实例的say_hello方法
person.say_hello()
在上面的例子中,首先创建了一个Person类的实例person,使用person.__init__("Alice", 30)调用了实例的init方法,该方法会重新初始化实例的name和age属性。然后,调用person.say_hello()方法打印实例的信息。输出结果为:
Hello, my name is Alice and I am 30 years old.
原文地址: https://www.cveoy.top/t/topic/jgPg 著作权归作者所有。请勿转载和采集!