Dzwebs.Net

撰写电脑技术杂文十余年

python类的综合使用1:类中有类,输出类对象及内容

Admin | 2026-3-9 22:53:24 | 被阅次数 | 3

温馨提示!

如果未能解决您的问题,请点击搜索;登陆可复制文章,点击登陆

python类的综合使用1:类中有类,输出类对象及内容

class eachstuinfor:
    def __init__(self,name,score):
        self.name=name
        self.score=score
    def __str__(self):#输出变量
        return str(self.__dict__)
    def __repr__(self):#输出对象
        # 复用 __str__ 的逻辑,保证格式统一
        return self.__str__()
class allstuinfor:
    def __init__(self):
        self.allstuinfor = []
    def add(self,e):
        self.allstuinfor.append(e)
    def get_sum(self):
        stulscorelist =[e.score for e in self.allstuinfor]
        return sum(stulscorelist)
    def printall(self):
        print("-"*36)
        for e in self.allstuinfor:
            print(e)
        #print(e.__dict__)
    def sortbyscore(self,reverse):
        self.allstuinfor.sort(key=lambda e:e.score,reverse=reverse)
    def __str__(self):
        return str(self.allstuinfor)
a1 =  allstuinfor()
a1.add(eachstuinfor("lucy",300.0))
a1.add(eachstuinfor("mask",298.0))
a1.add(eachstuinfor("blus",299.0))
a1.add(eachstuinfor("alice",300.0))
#print(a1)
print(a1.get_sum())
a1.printall()
a1.sortbyscore(True)
a1.printall()

输出如下内容:
1197.0
------------------------------------
{'name': 'lucy', 'score': 300.0}
{'name': 'mask', 'score': 298.0}
{'name': 'blus', 'score': 299.0}
{'name': 'alice', 'score': 300.0}
------------------------------------
{'name': 'lucy', 'score': 300.0}
{'name': 'alice', 'score': 300.0}
{'name': 'blus', 'score': 299.0}
{'name': 'mask', 'score': 298.0}


该杂文来自: 最新技术

上一篇:c++多线程共享数据与异步的实现

下一篇:暂时没有文章了

网站备案号:

网站备案号:滇ICP备11001339号-7

版权属性:

Copyright 2007-2021-forever Inc. all Rights Reserved.

联系方式:

Email:dzwebs@126.com QQ:83539231 访问统计