zoukankan      html  css  js  c++  java
  • 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:允许使用多重继承的设计

  • 相关阅读:
    php常用函数总结
    PHP常用函数(收集)
    Web开发者的最爱 5个超实用的HTML5 API
    打开MySQL数据库远程访问的权限
    centos yum 安装问题
    CentOS6.4安装VNC
    删:Centos 7安装Nginx 1.8
    centos6.3安装nginx
    MySQL5.7重置root密码
    CentOS下MySQL忘记root密码解决方法【转载】
  • 原文地址:https://www.cnblogs.com/finsomway/p/10042212.html
Copyright © 2011-2022 走看看