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

时间:2018-10-09 15:21:55

标签: python

我正在尝试对私有类中的列表进行排序,我可以对它进行排序而不会变得私有,但不能私有。

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

如何在私有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)

markdata:

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_

1 个答案:

答案 0 :(得分:0)

您为什么希望能够从课堂之外访问私有属性? The whole point of private attributes is to prevent that(Python makes it easy to work around it,但这样做显然违反了封装)。

如果变量应在逻辑上可读,并且主要将隐私用于防止写操作,则Student可以declare @property accessors

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

但是,如果不需要这种保护,则只需声明属性,而不首先使用前导__,然后将其公开。