📖 知识点
1. 读取对象属性
语法:对象.属性名
stu = Student("小明",16,88)
print(stu.name)
print(stu.score)
2. 修改对象已有属性
直接赋值即可:对象.属性名 = 新值
stu.score = 95
3. 动态新增属性
对象创建完成之后,可以临时给这个对象添加全新属性,只作用于当前这一个对象,不会影响同类其他实例。
stu.gender = "男"
完整示例代码
class Student:
def __init__(self, name, age, score):
self.name = name
self.age = age
self.score = score
stu1 = Student("小明",16,88)
# 读取属性
print("修改前分数:", stu1.score)
# 修改属性
stu1.score = 96
print("修改后分数:", stu1.score)
# 动态新增属性
stu1.gender = "男"
print("新增属性性别:", stu1.gender)
输出:
修改前分数: 88
修改后分数: 96
新增属性性别: 男
⚠️ 重点提醒
修改属性只影响当前这个对象,同类别的其他对象不受影响
动态新增的属性,只属于当前对象;别的同类型对象没有这个属性
如果访问不存在的属性,抛出
AttributeError
⚔️ Kata 实战任务
任务需求:
定义 Student 类,
__init__绑定 name, age, score实例化 stu1 = Student ("小红",15,92)
打印原始全部信息
修改小红的分数为 96
动态新增属性
city = "郑州"再次打印更新后的全部信息
参考代码
class Student:
def __init__(self, name, age, score):
self.name = name
self.age = age
self.score = score
stu1 = Student("小红", 15, 92)
print("==== 修改前 ====")
print(f"姓名:{stu1.name},年龄:{stu1.age},分数:{stu1.score}")
# 修改已有属性
stu1.score = 96
# 动态新增属性
stu1.city = "郑州"
print("==== 修改后 ====")
print(f"姓名:{stu1.name},年龄:{stu1.age},分数:{stu1.score},城市:{stu1.city}")
运行输出:
==== 修改前 ====
姓名:小红,年龄:15,分数:92
==== 修改后 ====
姓名:小红,年龄:15,分数:96,城市:郑州
🧠 思考题
再创建 stu2=Student ("小刚",16,75),直接打印 stu2.city,会发生什么?为什么?
除了外部直接赋值修改属性,上节课学的实例方法里面修改 self.score 有什么优势?
行者孙Python