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())
    
  • 相关阅读:
    spring-boot集成1:起步
    策略模式实现多种支付方式
    自定义切面实现记录系统操作日志
    Spring Kafka
    使用Keepalived实现Nginx高可用
    Centos7桥接网络、DNS、时间同步配置
    jmeter随笔(1)-在csv中数据为json格式的数据不完整
    (续篇3):飞测独家のJmeter秘籍,限量发放
    紧张:飞测独家のJmeter秘籍,限量发放(续篇2)
    紧张:飞测独家のJmeter秘籍,限量发放
  • 原文地址:https://www.cnblogs.com/yuexiao/p/15576606.html
Copyright © 2011-2022 走看看