创建一个类People 包含属性name, city python可以转换为字符串形式(__str__) 包含方法moveto(self, newcity) 可以按照city排序 创建4个人对象,放到列表进行排序
时间: 2023-12-03 13:46:22 浏览: 104
下面是创建类People的代码实现:
```python
class People:
def __init__(self, name, city):
self.name = name
self.city = city
def __str__(self):
return "{}: {}".format(self.name, self.city)
def moveto(self, newcity):
self.city = newcity
```
我们可以先创建4个人对象,然后将它们放到一个列表中,再按照city排序。下面是完整的代码实现:
```python
# 定义People类
class People:
def __init__(self, name, city):
self.name = name
self.city = city
def __str__(self):
return "{}: {}".format(self.name, self.city)
def moveto(self, newcity):
self.city = newcity
# 创建4个人对象
p1 = People("Tom", "New York")
p2 = People("Jerry", "Paris")
p3 = People("Alice", "London")
p4 = People("Bob", "Beijing")
# 将4个人对象放到一个列表中
people_list = [p1, p2, p3, p4]
# 按照city排序
people_list.sort(key=lambda x: x.city)
# 打印排序后的结果
for p in people_list:
print(p)
```
输出结果:
```
Bob: Beijing
Jerry: Paris
Alice: London
Tom: New York
```
阅读全文