【高级特性】47、上机练习:类和对象【高级特性】47、上机练习:类和对象
- 创建一个类People
包含属性name,city
可以转换为字符串形式(_str_)
包含方法moveto(self,newcity)
可以按照city排序
创建4个人对象,放到列表进行排序
class People:
def __init__(self, name, city):
self.name = name
self.city = city
def __str__(self):
return ''%(self.name,self.city)
__repr__ = __str__
def moveto(self,newcity):
newcity = self.newcity
def __lt__(self,other):
return self.city
- 创建一个类Teacher
是People的子类,新增属性school
moveto方法改为newschool
按照school排序
创建4个教师对象,放到列表进行排序
class Teacher(People):
def __init__(self, name, city, school): # 继承父类,并添加子类独有属性
super().__init__(name, city) # super函数用来调用已经在子类中重写过的父类方法
self.school = school
def __lt__(self, other):
return self.school > other.school
def newschool(self, ns):
self.school = ns
def __repr__(self): # repr特殊函数返回字符串
return f'{self.name},{self.school}'
f = []
f.append(Teacher('jack', 'fjing', '北大'))
f.append(Teacher('Lucy', 'shanghai', '复旦'))
f.append(Teacher('Tom', 'guangdong', '澳大'))
f.append(Teacher('rose', 'hunan', '湖大'))
print("original:", f)
f.sort()
print("sorted:", f)
- 创建一个mylist类,继承自内置数据类型list(列表)增加一个方法“累乘”product
def product(self):
返回所有数据项的乘积
class mylist(list):
def product(self):
s = 1
for i in self:
s *= i
return s
R = mylist([2, 3, 4, 5])
cj = R.product()
print(cj)
赞赏微信赞赏支付宝赞赏