其他分享
首页 > 其他分享> > 初学类_(1)

初学类_(1)

作者:互联网

# 类的创建、类的继承

# ************************ 定义类 ****************************
# 创建一个类People
class People:
    # 包含属性name、city
    def __init__(self, name, city):
        self.name = name
        self.city = city

    # 方法moveto
    def moveto(self, newcity):
        self.city = newcity

    # 按照city排序
    def __lt__(self, other):
        return self.city < other.city

    # 易读字符串表式
    def __str__(self):
        return '<%s,%s>' % (self.name, self.city)

    # 正式字符串表示
    __repr__ = __str__


# 类继承
# 创建一个类Teacher,是People的子类
class Teacher(People):
    # 新增属性school
    def __init__(self, name, city, school):
        super().__init__(name, city)  # super() 表示父类
        self.school = school

    # moveto方法改为newschool
    def moveto(self, newschool):
        self.school = newschool

    # 易读字符串表式
    def __str__(self):
        return '<%s,%s,%s>' % (self.name, self.city, self.school)

    # 正式字符串表示
    __repr__ = __str__


# 创建一个mylist类,继承内置数据类型list(列表)
class Mylist(list):

    # 增加一个方法:累乘product
    def product(self):
        # print(self)
        result = 1
        for item in self:
            result *= item
        return result


# ************************ 调用类 ****************************

# 创建4个人对象,放到列表进行排序

peo = list()
peo.append(People('迈克', '巴中'))
peo.append(People('橙子', '简阳'))
peo.append(People('酷米', '雅安'))
peo.append(People('安妮', '内江'))
print(peo)
peo[3].moveto('成都')
peo.sort()
print(peo)

# 创建4个教师对象,放到列表进行排序

tea = list()
tea.append(Teacher('michael','chengdu','1st school'))
tea.append(Teacher('orange','jianyang','2nd school'))
tea.append(Teacher('koomi','yaan','3rd school'))
tea.append(Teacher('annie','neijiang','1st school'))
print(tea)
tea[1].moveto('first school')
tea.sort()
print(tea)



ml = Mylist([1,2,3])
print(ml.product())

标签:__,city,school,tea,self,初学,peo
来源: https://www.cnblogs.com/yuexiao/p/15576606.html