zoukankan      html  css  js  c++  java
  • 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)

  • 相关阅读:
    css 权威指南笔记
    angular directive restrict 的用法
    vim 的寄存器
    以普通用户启动的Vim如何保存需要root权限的文件
    jshint options
    如何在Ubuntu Linux上安装Oracle Java
    Linux:使用nohup让进程在后台可靠运行
    反射-----学习Spring必学的Java基础知识之一
    java异常捕获
    cookie
  • 原文地址:https://www.cnblogs.com/ZHang-/p/10133333.html
Copyright © 2011-2022 走看看