实例变量是属于类实例的变量。从类中创建的每个对象都有这些变量的独立副本。与所有实例共享的类变量不同,实例变量为每个对象存储独特的数据。
想象一下:如果你和我都报名参加了在线 Python 课程,我们每个人都有自己的登录凭证。课程(类)是相同的,但我们的用户名(实例变量)是唯一的!
如何在 Python 中定义实例变量要定义实例变量,需要在类中使用 self 关键字。让我们看看一个简单的例子:
class Student: def __init__(self, name, age): self.name = name # Instance variable self.age = age # Instance variable# Creating instancesstudent1 = Student("Harish", 20)student2 = Student("Chandru", 22)print(student1.name) # Output: Harishprint(student2.age) # Output: 22在这个例子中,name 和 age 是实例变量。每个 Student 对象都有自己这些变量的值。
实例变量存储在哪里?实例变量存储在对象的 __dict__ 属性中。可以使用以下方法进行检查:
print(student1.__dict__)这将输出:
{'name': 'Harish', 'age': 20}每个实例都有自己的 __dict__,只存储其特定的数据。
实例变量与类变量的区别特征实例变量类变量定义在 __init__() 方法中外部 __init__() 属于单个实例整个类的变化只影响一个实例所有实例
类变量的示例:
class Course: category = "Programming" # Class variable def __init__(self, name): self.name = name # Instance variablecourse1 = Course("Python Basics")course2 = Course("Java Basics")print(course1.category) # Output: Programmingprint(course2.category) # Output: Programming修改实例变量您可以这样修改特定对象的实例变量:
student1.age = 21 # Changing Harish's ageprint(student1.age) # Output: 21这次更改不会影响其他实例,例如 student2。
想了解更多关于访问和修改实例变量的信息,请查看 PYnative。
实例变量常见问题解答1. 如果访问一个不存在的实例变量会发生什么?Python 将引发一个 属性错误 :
print(student1.grade) # AttributeError: 'Student' object has no attribute 'grade'2. 实例变量能否在__init__外部创建?是的!您可以在之后添加它们:
student1.grade = "A"print(student1.grade) # Output: A3. 该如何删除一个实例变量?使用 del:
del student1.ageprint(student1.age) # Raises AttributeError。