实例变量是在实例化对象时创建的。实例变量是对象的属性,可以在任何方法中使用,包括__init__和其他方法。 给个·例子
时间: 2023-06-01 15:03:37 浏览: 142
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
person1 = Person("John", 25)
person2 = Person("Alice", 30)
person1.greet()
person2.greet()
# Output:
# Hello, my name is John and I am 25 years old.
# Hello, my name is Alice and I am 30 years old.
In this example, the class Person has two instance variables, name and age, which are created when the objects person1 and person2 are instantiated. These instance variables can be accessed and used in any method of the class, including the greet method, which prints out a greeting message using the name and age of the person.
阅读全文