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

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

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

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

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

(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:允许使用多重继承的设计

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄