我正在尝试按姓氏对所有患者对象进行分组。
我的代码:
class Patient:
def __init__(self, first_name, surname, age, mobile, postcode):
self.__first_name = first_name
self.__surname = surname
self.__doctor = "None"
self.__age = age
self.__mobile = mobile
self.__postcode = postcode
self.__symptoms = ""
def full_name(self) :
return "{} {}".format(self.__first_name, self.__surname)
def __str__(self):
return f'{self.full_name():^20}|{self.__doctor:^6}|{self.__age:^4}|{self.__mobile:^15}|{self.__postcode:^10}'
patients = [Patient('Sara','Cath', 20, '07012345678','B1 234'),
Patient('Mike','Abe', 37,'07555551234','L2 2AB'),
Patient('Daivd','Barr', 15, '07123456789','C1 ABC'),
Patient('Gerald','Abe', 21, '07012345678','L2 2AB'),
Patient('Sara','Abe', 19, '07012345678','L2 2AB'),
Patient('Jane','Barr', 35, '07123456789','C1 ABC')]
patients.sort(key=lambda y: y.__surname)
print(patients[0])
print(patients[1])
print(patients[2])
print(patients[3])
print(patients[4])
print(patients[5])
print()
newPat = sorted(patients, key=lambda y: y.__surname)
print(newPat[0])
print(newPat[1])
print(newPat[2])
print(newPat[3])
print(newPat[4])
print(newPat[5])
我的代码在
self.__surname = surname
函数、__init__
函数和两个排序函数中具有姓氏属性 full_name
,但是当我尝试运行时,它给出了 AttributeError: 'Patient' object has no attribute '__surname'
错误:
File "c:\users\mundane\downloads\pythonfiles\files\untitled0.py", line 25, in <lambda>
patients.sort(key=lambda y: y.__surname)
AttributeError: 'Patient' object has no attribute '__surname'
如果我将四个
.__surname
中的每一个替换为其他任何东西 - 例如 .xyzsurname
- 它可以工作并正确打印:
Mike Abe | None | 37 | 07555551234 | L2 2AB
Gerald Abe | None | 21 | 07012345678 | L2 2AB
Sara Abe | None | 19 | 07012345678 | L2 2AB
Daivd Barr | None | 15 | 07123456789 | C1 ABC
Jane Barr | None | 35 | 07123456789 | C1 ABC
Sara Cath | None | 20 | 07012345678 | B1 234
Mike Abe | None | 37 | 07555551234 | L2 2AB
Gerald Abe | None | 21 | 07012345678 | L2 2AB
Sara Abe | None | 19 | 07012345678 | L2 2AB
Daivd Barr | None | 15 | 07123456789 | C1 ABC
Jane Barr | None | 35 | 07123456789 | C1 ABC
Sara Cath | None | 20 | 07012345678 | B1 234
我是否可以通过使用另一种方式来排序对象列表来保留属性的双下划线?
您可以使用内置的
dir()
方法来找出您的 Patient 对象 具有哪些属性。运行会产生:
['_Patient__age',
'_Patient__doctor',
'_Patient__first_name',
'_Patient__mobile',
'_Patient__postcode',
'_Patient__surname',
'_Patient__symptoms',
'__class__',
'__delattr__',
'__dict__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__le__',
'__lt__',
'__module__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'__weakref__',
'full_name']
您可以看到,因为您使用的是双下划线(意味着这些属性不打算与类外部交互),所以 Python 将它们隐藏为 _Patient__surname
。因此,如果您将排序更改为
patients.sort(key=lambda y: y._Patient__surname)
,它将起作用