Python 元类

  • 什么是元类 - 类的类

元类 ------->  类  ------>  类的对象

Python中一切皆对象。

class Person(object):
    name = 'Sam'
    def hello():
        print('hello')

p = Person()

 

对象p是从类Person创建, 那么Person对象是怎么从类型type创建出来的呢?

类的三要素 : 名字 基类 属性

Person = type('Person', (object, ), { 'name':'nnn', 'hello': lambda self : print('hello')})

 

  • 自定义元类控制类的创建过程
  1. 自定义元类
class MetaA(type):
    pass

2. 元类创建类的过程

  1. __new__
  2. __init__

 

class Person():
    def __new__(cls, name, sex):
        print('Person.__new__')
        p = super().__new__(cls)
        return p
    def __init__(self, name, sex):
        print('Person.__init__')
        self.name = name
        self.sex = sex

p = Person('Jack', 'male')
print(p.__dict__)

class MetaA(type):
    def __new__(cls, name, bases, dct):
        print('MetaA.__new__')
        cl = super().__new__(cls, name, bases, dct)
        return cl
    def __init__(self, name, bases, dct):
        print('MetaA.__init__')
        pass

  

* 练习 自定义属性变大写

 

  • 控制自定义类的调用方式

 

class Person(metaclass=MetaA):
    def __new__(cls, name, sex):
        p = super().__new__(cls)
        return p
    def __init__(self, name, sex):
        self.name = name
        self.sex = sex  

p = Person('Jack', 'male')class MetaA(type):
    def __call__(self, name, sex):
        pass

 

* 练习 - 改写__cal__, 使类不需要定义__init__方法

  • 属性查找
    type
      |
      |
   metaclass
      |
----------------------------------------------
      ClassD -> ClassB -> object

 

class MetaA(type):
    s = 'metaa'
class Person():
    s = 'person'class Worker(Person, metaclass=MetaA):
    pass

print(Worker.s)

 

  

posted on 2019-07-20 15:21  fanchuanster  阅读(111)  评论(0编辑  收藏  举报

导航