题目:
创建一个类people
包含属性name,city
可以转换为字符串形式(str)
包含方法moveto(self,newcity)
可以按照city排序
创建4个人对象,放到列表进行排序
IDE:
Thonny
遇到的问题
1 运行显示:
添加下行代码,问题得到解决
__repr__=__str__
2 def定义类函数的时候,return和print都能输出,不确定用哪个
print:只打印语句,不传递值
参考:https://blog.csdn.net/cpc784221489/article/details/90666442
代码
# 类名用大写字母开头
class People:
def __init__(self,name,city):
# 用于根据类的定义创建实例对象
self.name=name
self.city=city
def __str__(self):
return'<%s:%s>'%(self.name,self.city)
def moveto(self,newcity):
newcity=self.newcity
def __lt__(self,other):
return self.city<other.city
# city.sort()
# moveto是方法
__repr__=__str__
p=list()
p.append(People("Jenny",'Wuhan'))
p.append(People("Erica",'Beijing'))
p.append(People("Celia",'Guangdong'))
p.append(People("David",'Cesuo'))
print("Original:",p)
p.sort()
print("Sorted:",p)