码迷,mamicode.com
首页 > 编程语言 > 详细

Python第八周 学习笔记(1)

时间:2018-05-13 15:04:25      阅读:252      评论:0      收藏:0      [点我收藏+]

标签:学习笔记

继承
  • 基本概念个体继承自父母,继承了父母的一部分特征,但也可以有自己的个性
  • 子类继承了父类,就直接拥有了父类的属性和方法,也可以定义自己的属性、方法,甚至对父类的属性、方法进行重写

Python继承实现

  • class Cat(Animal) 括号中为该类的父类列表

  • 如果类定义时没有父类列表,则只继承object类
  • object类是所有类的祖先类

类的特殊属性与方法

  • base
    • 类的基类
  • bases
    • 类的基类的元组
  • mro
    • 方法解析时的类的查找顺序,返回元组
  • mro()
    • 作用同上,返回列表
  • subclasses()
    • 返回类的子类的列表

Python继承中的注意事项

  • 属于父类的私有成员,子类即使与父类存在继承关系也不可直接访问(可通过改名后的属性名访问,但慎用)
  • 例子:

class Animal:
    __count=100
    heigtht=0

    def showcount3(self):
        print(self.__count)

class Cat(Animal):
    name=‘cat‘
    __count=200

c=Cat()
c.showcount3()

结果为100

因为子类调用了父类获取父类私有变量的方法 self.count的count作用域是在父类下的,其真正调用的self._Animal__count,而这个属性只有父类有

  • 解决的办法:自己私有的属性,用自己的方法读取和修改,不要借助其他类的方法,即使是父类或派生类的方法

属性查找顺序

  • 实例dict -> 类dict -> 父类dict

多继承

Mixin

  • 本质是多继承
  • 体现的是一种组合的设计模式

Mixin类使用原则

  • 类中不应该显示的出现init初始化方法
  • 通常不能独立工作,因为它是准备混入别的类中的部分功能实现
    其祖先类也应是Mixin类

  • 使用Mixin时,其通常在继承列表的第一个位置

  • 装饰器实现

def printable(cls):
    def _print(self):
        print(self.content, ‘decorator‘)

    cls.print = _print
    return cls

class Document:
    def __init__(self, content):
        self.content = content

class Word(Document):
    pass

class Pdf(Document):
    pass

@printable
class PrintableWord(Word): pass

print(PrintableWord.__dict__)
print(PrintableWord.mro())

pw = PrintableWord(‘test string‘)
pw.print()

@printable
class PrintablePdf(Word):
    pass
  • 优点:
    • 简单方便,在需要的地方动态增加,直接使用装饰器

Mixin实现


class Document:
    def __init__(self, content):
        self.content = content

class Word(Document):
    pass

class Pdf(Document):
    pass

class PrintableMixin:
    def print(self):
        print(self.content, ‘Mixin‘)

class PrintableWord(PrintableMixin, Word):
    pass

print(PrintableWord.__dict__)
print(PrintableWord.mro())

pw = PrintableWord(‘test string‘)
pw.print()

class SuperPrintableMixin(PrintableMixin):
    def print(self):
        print(‘~‘ * 20)
        super().print()
        print(‘~‘ * 20)

class SuperPrintablePdf(SuperPrintableMixin, Pdf):
    pass

print(SuperPrintablePdf.__dict__)
print(SuperPrintablePdf.mro())

spp = SuperPrintablePdf(‘super print pdf‘)

spp.print()

Mixin类和装饰器

  • 这两种方式都可以使用,看个人喜好
  • 如果还需要继承就得使用Mixin类

Python第八周 学习笔记(1)

标签:学习笔记

原文地址:http://blog.51cto.com/11281400/2115683

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!