• Python学习之旅(十九)


    Python基础知识(18):面向对象高级编程(Ⅰ)

    使用__slots__:限制实例的属性,只允许实例对类添加某些属性

    (1)实例可以随意添加属性

    (2)某个实例绑定的方法对另一个实例不起作用

    (3)给类绑定方法市所有类都绑定了该方法,且所有实例都可以调用该方法

    用__slots__定义属性反对这个类的实例起作用,但对这个类的子类是不起作用的

    >>> class Student(object):
        __slots__=("name","age")
    
        
    >>> s=Student()
    >>> s.name="Jack"
    >>> s.score=90
    Traceback (most recent call last):
      File "<pyshell#43>", line 1, in <module>
        s.score=90
    AttributeError: 'Student' object has no attribute 'score'

    使用@property:把方法变成属性来调用

    @property是Python内置的装饰器

    >>> class Student(object):
        @property
        def test(self):
            return self.name
        @test.setter
        def test(self,name):
            self.name=name
    
            
    >>> s=Student()
    >>> s.test="Alice"
    >>> print(s.test)
    Alice

     

    多重继承

    通过多重继承,子类可以同时获得多个父类的所有功能

    >>> class Run(object):
        def run():
            print("I can run.")
    
            
    >>> class Fly(object):
        def fly():
            print("I can fly.")
    
            
    >>> class Swim(object):
        def swim():
            print("I can swim.")
    
            
    >>> class Duck(Run,Fly,Swim):
        pass

    Mixln:允许使用多重继承的设计

  • 相关阅读:
    Pieczęć(模拟)
    【并查集】关押罪犯
    火车进栈
    独木舟上的旅行
    哈尔滨理工大学第八届程序设计团队赛K题
    [数学、递推]Everything Is Generated In Equal Probability
    [构造]triples I
    2019牛客第三场
    [DP]销售
    [哈夫曼树]猜球球
  • 原文地址:https://www.cnblogs.com/finsomway/p/10042212.html
Copyright © 2020-2023  润新知