zoukankan      html  css  js  c++  java
  • 初学类_(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())
    
  • 相关阅读:
    debian8.4 ibus中文输入法
    C++成员变量的初始化顺序问题
    debian及ubuntu挂载本地硬盘的ISO镜像文件
    linux中eth0原何变成了eth1
    debian8.4 ubuntu14.04双系统_debian8.4硬盘安装
    oracle:delete和truncate
    数组指针与指针数组(good)
    Intel 8086_通用寄存器|段寄存器
    linux shell 不同进制数据转换(二进制,八进制,十六进制,base64)
    shell中exec命令
  • 原文地址:https://www.cnblogs.com/yuexiao/p/15576606.html
Copyright © 2011-2022 走看看