张拽拽

导航

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)

 

posted on 2018-12-17 19:25  张拽拽  阅读(110)  评论(0编辑  收藏  举报