python :类练习

本文介绍了如何使用Python的os模块递归遍历目录,展示了一个四层深的目录结构。此外,通过random库的choices和sample方法,生成了两组共8个分数,确保它们的平均值为80,且分数分布在指定范围内。最后,定义了一个Person类,展示了如何使用__new__和__init__方法,并创建了两个实例,调用了print_info方法打印信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.使用递归去列出当前目录下的所有文件(格式要求:分层输出)
要求:最少4层目录:比如:
test:
-test.txt
-test_data.xls
-test1
-test1.txt
-test_data1.txt
-test2
-test2.txt
-test2_data.txt
-test3
-test3.txt
-test3_data.txt

import os
def fun(path):
    print(end='\t')
    list_mulu = os.listdir(path)
    for i in list_mulu:
        a = os.path.join(path,i)
        if os.path.isdir(a):
            print(i)
            print(end='\t')
            fun(a)
        else:
            print(end='\t')
            print(i)
            print(end='\t')


path = 'd:\\1'
print("1")
fun(path)

2.# 给定一个成绩score,随机出8个分数 =》 8个分输之和/8 = 80,
#8个分数的分布,score - 10 < score < score + 10
提示使用random中choices和sample

import random
while True:
    list_1 = random.sample(range(70,81),4)
    list_2 = random.sample(range(80,91),4)
    mun = sum(list_1)+sum(list_2)
    if mun/8 == 80:
        break
    else:
        print('0')
print(list_1[0],list_1[1],list_1[2],list_1[3],\
      list_2[0],list_2[1],list_2[2],list_2[3]

3.定义一个类:Person
类属性:type=“student”
对象属性:name, age, gender
方法:print_info: 打印内容:某某 is a good student.
在类中重写:__new____init__,并打印__new__和__init__来显示已调用
实例化两个对象: zhangsan, lisi且调用方法:

class person():
    type = 'student'
    def __init__(self,name,age,gender):
        self.name = name
        self.age = age
        self.gender = gender
        print("__init__")
    def print_info(self):
        print(f'{self.name} is good {self.type}')
zhangsan = person('zhangsan', 20, '男')
lisi = person('lisi', 22, '女')
zhangsan.print_info()
lisi.print_info()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值