Python:如何在另一个程序私有类中对列表排序

Python:如何在另一个程序私有类中对列表排序,python,Python,我正在尝试对私有类中的列表进行排序,我可以在不使用私有类的情况下对其进行排序,但在私有类中无法进行排序 首先,我打开数据并将其拆分到main.py中,然后在main.py中设置一个名为StudentDL的列表,并将其命名为Student.py,如果我使用private Student.py,则无法在main.py中对StudentDL列表进行排序 如何在private Student.py之后对main.py或Student.py中的StudentDL列表进行排序 Main.py: from S

我正在尝试对私有类中的列表进行排序,我可以在不使用私有类的情况下对其进行排序,但在私有类中无法进行排序

首先,我打开数据并将其拆分到main.py中,然后在main.py中设置一个名为StudentDL的列表,并将其命名为Student.py,如果我使用private Student.py,则无法在main.py中对StudentDL列表进行排序

如何在private Student.py之后对main.py或Student.py中的StudentDL列表进行排序

Main.py:

from Student import Student

StudentDL = []
file = open('markdata.dat', 'r')
line = file.readline()

while line != '':
    StudentRec = line.split('_')
    StudentDL.append(Student(int(StudentRec[0]),str(StudentRec[1]),
                            float(StudentRec[2]),
                            float(StudentRec[3])))
    line = file.readline()
file.close()
for e in StudentDL:
    print (e)
for e in sorted(StudentDL, key=lambda c:c.sID):
    print (e)
print('='*20)
for e in sorted(StudentDL, key=lambda c:c.n):
    print (Student.overall(e))
Student.py:

class Student(object):
    numStudent = 0 
    def __init__(self,studentID,name,cwmark,exammark):
        Student.numStudent += 1
        self.__sID = studentID
        self.__n = name
        self.__cwm = cwmark
        self.__exm = exammark
        self.__om = (cwmark*0.4)+(exammark*0.6)

    def __str__(self):
        return '%-15s%-27s%-10.2f%7.2f'%\
            (self.__sID,self.__n,self.__cwm,self.__exm)

    def overall(self):
        return '%-15s%-27s%-12.2f%-7.2f%8.2f'%\
            (self.__sID,self.__n,self.__cwm,self.__exm,self.__om)

    def getoverall(self):
        return float(self.__om)
标记数据:

50123456_lam tai man_70.0_60.0_
50223456_li tai man_60.0_90.5_
50323456_wong tai man_34.5_30.0_
50423456_ng tai man_90.5_70.0_
50523456_lau tai man_86.0_92.4_
50623456_chui tai man_70.0_64.5_
50723456_lim tai man_64.5_60.0_
50823456_pok tai man_37.5_35.50_
50923456_kim tai man_92.4_60.0_
50023456_tsang tai man_15.0_20.0_
50999999_chan peter_100.00_80.00_

为什么您希望能够从类外部访问私有属性?(Python,但这样做时显式违反了封装)

如果变量应具有逻辑可读性,且隐私主要用于防止写入,
Student
可以:


但是,如果不需要这种保护,那么首先只需声明您的属性而不使用前导的
\uuu
,并将其公开。

我知道我的问题很愚蠢。。但我的老师告诉我们,使用提交私人类的程序,并有一个排序功能。他给出的建议是在私人课堂上进行分类,我真不知道该怎么办…@WongYatCheongJacky:你的老师是不是想通过定义
\uu lt\uuu
和来让课堂实例具有可比性?这允许您定义类实例的自然顺序,并且由于类上定义了
\uuuult\uuuu
,因此它可以访问私有成员。类似地,定义
@property
访问器将使底层属性保持私有,同时提供公共只读访问(这将允许您根据属性定义
key
函数)。我尝试使用lt方法,但在TypeError上显示了一个错误:uuuu lt_uuuuuuuuuuuu()缺少一个必需的位置参数:“other'@WongYatCheongJacky:您不直接调用
\uuuu lt\uuuuuuuuuuuuu
(这不是禁止的,但这样做很愚蠢,在您使用它的场景中,没有任何意义)。它只是一个在测试
studenta
时自动调用的函数,Python的排序函数在未定义
key
函数(或者对象是
键的一部分)时隐式使用它作为默认比较。如果
\uu lt\uuu
定义正确,则只需对排序中的e执行
(StudentDL):
而不传递
函数,然后按排序顺序进行迭代。
class Student(object):
    numStudent = 0 
    def __init__(self,studentID,name,cwmark,exammark):
        ...

    @property
    def n(self):
        return self.__n

    @property
    def sID(self):
        return self.__sID