class person:
def __init__(self,name=None,age=None):
self.name=name
self.age=age
def __str__(self):
return '我是{0},今年{1}岁'.format(self.name,self.age)
def __add__(self, other):
return person(self.name+other.name,self.age+other.age)
def __cmp__(self, other):
return self.name
# def __lt__(self,other):
# if self.name==other.name:
# return other.age<self.age
# else:
# return self.name.encode('gbk')<other.name.encode('gbk')
print(‘——————————-‘)
ps=[person(‘asdf’,10),person(‘zhangsan’,19),]
for p1 in ps:
print(p1)
print(‘——————————’)
for p1 in sorted(ps,key=lambda a:(a.name.encode(‘gbk’),-a.age)):
print(p1)
本文介绍了一个简单的Python类定义实例,展示了如何创建Person类并实现__init__、__str__、__add__等方法。同时,通过具体示例演示了如何使用这些方法以及如何对对象列表进行排序。
31万+

被折叠的 条评论
为什么被折叠?



