python中的类型转换类:如何实现?
在这里,我试图将一个社交媒体档案模拟为一个类“档案”,在这个类中,你有名字、一组朋友以及添加和删除朋友的能力。我想做一个方法,当调用它时,它会按字母顺序打印朋友列表 问题:我得到一个警告,我不能对不可排序的类型进行排序。Python将我的实例变量视为“Profile对象”,而不是我可以排序和打印的列表 这是我的密码:python中的类型转换类:如何实现?,python,class,oop,Python,Class,Oop,在这里,我试图将一个社交媒体档案模拟为一个类“档案”,在这个类中,你有名字、一组朋友以及添加和删除朋友的能力。我想做一个方法,当调用它时,它会按字母顺序打印朋友列表 问题:我得到一个警告,我不能对不可排序的类型进行排序。Python将我的实例变量视为“Profile对象”,而不是我可以排序和打印的列表 这是我的密码: class Profile(object): """ Represent a person's social profile Argument:
class Profile(object):
"""
Represent a person's social profile
Argument:
name (string): a person's name - assumed to uniquely identify a person
Attributes:
name (string): a person's name - assumed to uniquely identify a person
statuses (list): a list containing a person's statuses - initialized to []
friends (set): set of friends for the given person.
it is the set of profile objects representing these friends.
"""
def __init__(self, name):
self.name = name
self.friends = set()
self.statuses = []
def __str__(self):
return self.name + " is " + self.get_last_status()
def update_status(self, status):
self.statuses.append(status)
return self
def get_last_status(self):
if len(self.statuses) == 0:
return "None"
else:
return self.statuses[-1]
def add_friend(self, friend_profile):
self.friends.add(friend_profile)
friend_profile.friends.add(self)
return self
def get_friends(self):
if len(self.friends) == 0:
return "None"
else:
friends_lst = list(self.friends)
return sorted(friends_lst)
在我填写朋友列表(来自测试模块)并调用get_friends方法后,python告诉我:
File "/home/tjm/Documents/CS021/social.py", line 84, in get_friends
return sorted(friends_lst)
TypeError: unorderable types: Profile() < Profile()
文件“/home/tjm/Documents/CS021/social.py”,第84行,在get_friends中
已排序的返回(朋友)
TypeError:无序类型:Profile()
为什么我不能简单地键入对象以列表形式获取它?我应该怎么做才能让get_friends返回按字母顺序排序的朋友列表?排序算法查找是否存在
\uuuuueq\uuuu
,\uu ne\uuuuu
,\uu lt\uuuuuuuu
,\uuu gt\uuuuuu
,类定义中的\uuuu ge\uuuuu
方法来比较从它们创建的实例。您需要重写这些方法以调整它们的行为
出于性能方面的考虑,我建议您为类定义一些integer
属性,如id
,并将其用于比较,而不是使用具有字符串比较开销的name
class Profile(object):
def __eq__(self, profile):
return self.id == profile.id # I made it up the id property.
def __lt__(self, profile):
return self.id < profile.id
def __hash__(self):
return hash(self.id)
...
使用操作符.attrgetter
>>> import operator
>>> new_friend_list = sorted(friend_list, key=operator.attrgetter('id'))
我想我要试试这个。首先,以下是代码:
from collections import namedtuple
class Profile(namedtuple("Profile", "name")):
def __init__(self, name):
# don't set self.name, it's already set!
self.friends = set({})
self.statuses = list([])
# ... and all the rest the same. Only the base class changes.
我们在这里所做的是创建一个具有元组形状的类。因此,它是可排序的、可散列的以及所有的东西。你甚至可以放弃你的
\uu str\uu()
方法,namedtuple
提供了一个很好的方法 简单的解决方案:returnsorted(friends\u lst,key=lambda x:x.name)
放在一边,list([])
和set({})是多余的,[]
和set()
是多余的sufficient@AshwiniChaudhary我确实在用蟒蛇3。上面的建议仍然打印对象及其在内存中的位置,而不是列表。为什么会这样?@ThomasMatthew因为您还没有定义\uuu repr\uu
方法。list、tuple、dict等容器通常显示对象的repr(
)版本。@ThomasMatthew也正如IfLoop所指出的,不要将{}
与集合混淆。这是一个非常常见的错误,要获取空集,请使用set()
。虽然set({})
可以工作,但这不是正确的方法。@Cthulhu OP显然正在使用Python 3,其中\uuuu cmp\uuuu
不再可用。请注意,此解决方案将不起作用,因为现在实例不再是可散列的,因此下面几行self.friends.add(friends\u profile);friend\u profile.friends.add(self)
将引发错误。@ozgur感谢您为我的问题提供了这么多备选方案,并向我介绍了操作员模块。看来我有一些书要读。再次感谢这给了我一个非常接近我想要的输出。非常感谢。有一个keyrerror:Profile(name='Bob'),这很奇怪。这是否意味着bob正试图从他不是朋友的个人资料中删除?
from collections import namedtuple
class Profile(namedtuple("Profile", "name")):
def __init__(self, name):
# don't set self.name, it's already set!
self.friends = set({})
self.statuses = list([])
# ... and all the rest the same. Only the base class changes.