• Python_day8


    • 多态
    class Animal(object):
        def run(self):
            print('animal is running')
    
    
    class Dog(Animal):
        def run(self):
            print('Dog run fast')
    
    
    class Rabbit(Animal):
        def run(self):
            print('Rabbit jump...')
    
    class Cat(Animal):
        pass
    
    class Timer(object):
        def run(self):
            print('the time is running')

    多态:同一种类型,不同的表现形式

    def runTwice(animal):
        animal.run()
        animal.run()
    
    a = Animal()
    rabbit = Rabbit()
    
    runTwice(a)
    runTwice(rabbit)

    鸭子类型

    tm = Timer()
    runTwice(tm)

    限制实例属性

    只允许由'name' 'age'属性

    class Person(object):
        __slots__ = ('name', 'age')
    per1 = Person()
    per1.name = '小明'
    print(per1.name)
    per1.height = 167 # 不允许
    class Student(object):
        def __init__(self, age):
            self.__age = age
    def setScore(self, score):
            if 0 <= score <= 100:
                self.__score = score
                return 'ok'
            else:
                return 'error'
                
        def getScore(self):
            return self.__score
    @property # 访问器 可以单独存在
        def score(self):
            print('getter is called')
            return self.__score
    
        @score.setter # 设置器 不单独存在,一定要有property
        def score(self, score):
            print('setter is called')
            if 0 <= score <= 100:
                self.__score = score
                return 'ok'
            else:
                return 'error'
    
        @ property
        def age(self):
            return self.__age
    
    
    s1 = Student(20)

    s1.score = 100
    print(s1.score)
    print(s1.age)

  • 相关阅读:
    mysql批量插入数据的基类
    mount命令解析
    常用linux命令记录
    转载一篇大神的博客文章
    linux查看网卡状态
    centos7配置网卡绑定
    coentos7安装python3
    阿里云ecs 硬盘在线扩容
    centos7安装redis5
    centos7 rpm安装nginx
  • 原文地址:https://www.cnblogs.com/ZHang-/p/10133333.html
Copyright © 2020-2023  润新知