29 ### 面向对象-类嵌套


class Student:

    def __init__(self, name, age):
        self.name = name
        self.age = age


s1 = Student('s1', 29)
s2 = Student('s2', 29)
s3 = Student('s3', 26)


# s1.name, s1.age
# s2.name, s2.age


class Cls:

    def __init__(self, title):
        self.title = title
        self.stu_list = []  # 定义学生列表为空


c1 = Cls("三年一班")
c2 = Cls("三年二班")

# c1.title, c1.stu_list = []
# c2.title

c1.stu_list.append(s1)  # 找到 c1.stu_list 这个列表,将Student类中对象:s1,s2添加到Cls的stu_list列表
c1.stu_list.append(s2)  # 找到 c1.stu_list 这个列表

c2.stu_list.append(s3)

# 需求:给你一个c1对象,请输入班名称和学员姓名

print(f"班级:{c1.title}")
for item in c1.stu_list:
    # 此时item = student 对象,对象中包含(name, age)
    print(f"学生姓名:{item.name},年龄:{item.age}")


class School:

    def __init__(self, city, cls):
        self.city = city
        self.cls_object = cls


obj = School("sc-cd", c1)
# obj.city                              # "sc-cd"
# obj.cls_object                        # 班级对象 (title, stu_list)
# obj.cls_object.title                  # 年级标题 三年级2班
# obj.cls_object.stu_list               # 学生列表:[学生对象(name, age),学生对象]
# obj.cls_object.stu_list[0].name       #取索引下标为:0 学生的姓名
# obj.cls_object.stu_list[0].age        #取索引下标为:0 学生的年龄
posted @   jhchena  阅读(3)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示