元类type

1. 创建类的两种方式 (都是由type元类创建)

方式一:

class Foo(object):      # 默认metaclass = type, 当前类, 由type类创建
a = 'aaa'
def func(self, x):
return x + 1

方式二:

Foo = type("Foo", (object, ), {'a': "aaa", 'func': lambda self, x: x + 1})

metaclass

作用:
  通过metaclass可以指定当前类由哪一个元类创建

python2和python3的区别:

    python3:
class Foo(object, metaclass=type):
pass python2:
class Foo(object):
__metaclass__=type
pass

自定义元类

1、第一步

class MyType(type):
def __init__(self, *args, **kwargs):
print("创建类之前")
super(MyType, self).__init__(*args, **kwargs)
print("创建类之后")

2、第二步

class Base(object, metaclass=MyType):
pass

Base = MyType('Base', (object, ), {})

这两部代码写完后,执行:

输出:

  创建类之前
  创建类之后

因为:  代码一执行, 就创建一个类,由MyType创建Foo类,就执行Mytype的__init__方法了

3、第三步

class Foo(Base):         # 基类由MyType创建,Bar也由MyType创建
a = 'aaa' def func(self, x):
return x + 1

现在有3个类, 运行脚本,会打印2遍("创建类之前","创建类之后")

元类__new__/__init__/__call__的执行顺序

class MyType(type):
def __init__(self, *args, **kwargs):
print("MyType: __init__")
super(MyType, self).__init__(*args, **kwargs) def __call__(self, *args, **kwargs):
print('MyType: __call__')
super(MyType, self).__call__(*args, **kwargs) def with_metaclass(arg):
return MyType('Base', (arg,), {}) class Foo(with_metaclass(object)):
a = 'aaa' def __init__(self, *args, **kwargs):
print('Foo: __init__')
super(Foo, self).__init__(*args, **kwargs) def __new__(cls, *args, **kwargs):
print('Foo: __new__')
return super(Foo, cls).__new__(cls) def func(self, x):
return x + 1 b = Foo() # MyType: __init__ 这个是创建Base类的时候执行MyType的__init__
# MyType: __init__ 创建Foo类的时候,执行MyType的__init__
# MyType: __call__ 实例化 Foo(), 先执行MyType的__call__, 再执行Foo的__new__和__init__
# Foo: __new__ 然后才会执行Foo的__new__方法
# Foo: __init__     最后执行Foo的__init__方法

总结:
  1. 默认类由type实例化创建。
  2. 某个类指定metaclass=MyType,那么当前类及所有派生类都由于MyType创建。
  3. 实例化对象
    - type.__init__

    - type.__call__
    - 类.__new__
    - 类.__init__

type和metaclass元类的更多相关文章

  1. python——type()、metaclass元类和精简ORM框架

    1.type()函数 if __name__ == '__main__': h = hello() h.hello() print(type(hello)) print(type(h)) Hello, ...

  2. metaclass元类解析

    一.创建类的流程 二.什么是元类 在Python3中继承type的就是元类 示例 # 方式一 class MyType(type): '''继承type的就是元类''' def __init__(se ...

  3. Python - metaclass元类

    参考 https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014319106919 ...

  4. Python - metaclass元类(图)

    个人总结

  5. Python面向对象篇之元类,附Django Model核心原理

    关于元类,我写过一篇,如果你只是了解元类,看下面这一篇就足够了. Python面向对象之类的方法和属性 本篇是深度解剖,如果你觉得元类用不到,呵呵,那是因为你不了解Django. 在Python中有一 ...

  6. python 元类 type metaclass

    python中一切皆对象,类对象创建实例对象,元类创建类对象,元类创建元类. 元类创建类对象有2中方式: 一.type方法 type(类名, 由父类名称组成的元组(针对继承的情况,可以为空),包含属性 ...

  7. Python面向对象 -- slots, @property、多重继承MixIn、定制类(str, iter, getitem, getattr, call, callable函数,可调用对象)、元类(type, metaclass)

    面向对象设计中最基础的3个概念:数据封装.继承和多态 动态给class增加功能 正常情况下,当定义了一个class,然后创建了一个class的实例后,可以在程序运行的过程中给该实例绑定任何属性和方法, ...

  8. 深刻理解Python中的元类metaclass(转)

    本文由 伯乐在线 - bigship 翻译 英文出处:stackoverflow 译文:http://blog.jobbole.com/21351/ 译注:这是一篇在Stack overflow上很热 ...

  9. 深刻理解Python中的元类(metaclass)

    译注:这是一篇在Stack overflow上很热的帖子.提问者自称已经掌握了有关Python OOP编程中的各种概念,但始终觉得元类(metaclass)难以理解.他知道这肯定和自省有关,但仍然觉得 ...

随机推荐

  1. web前端工程师入门须知

    本文是写给那些想要入门web前端工程的初学者,高手请路过,也欢迎高手们拍砖. 先说下web前端工程师的价值,目前web产品交互越来越复杂,用户使用体验和网站前端性能优化这些都得靠web前端工程师去做w ...

  2. phpstorm设置代码块快捷方式

    File -> Settings -> Live Templates

  3. Java集合类工具CollectionUtils的操作方法

    集合判断: 例1: 判断集合是否为空:CollectionUtils.isEmpty(null): trueCollectionUtils.isEmpty(new ArrayList()): true ...

  4. ES5函数新增的方法(call、apply、bind)

    1.call()的使用<script type="text/javascript"> var obj1 = { name:'bob', fn:function(){ c ...

  5. swift版本拼图游戏项目源码

    现学现做的第一个swift版本拼图游戏demo 常规模式,对换模式任你选择, 用到了花瓣的API,各种萌妹子~

  6. Photoshop 注册破解

    本机测试环境为Photoshop cs4 破解方式一: 打开C:\windows\system32\drivers\etc\"找到 hosts 文件, 右键点击--打开方式---记事本,然后 ...

  7. 在proe模型文件里面存储用户数据

    存储外部数据 author:visualsan 2014.2 上海 1.简介 利用外部数据存储外部接口,可以在模型文件里面尺寸用户自定义数据.在模型保存时数据自动存储,在模型载入时数据自动载入.外部数 ...

  8. Logisim的使用

    准备 通过Logisim的官网下载适合你机器的Logisim的软件,启动Logisim应用程序(Logisim可能有点bug,如果程序运行诡异,可能内部已经奔溃,最好的解决方法是重新启动它). Log ...

  9. OSI七层模型和TCP/IP五层模型详解

    OSI是一个开放性的通信系统互连参考模型,他是一个定义得非常好的协议规范.OSI模型有7层结构,每层都可以有几个子层. OSI的7层从上到下分别是 7 应用层 6 表示层 5 会话层 4 传输层 3 ...

  10. Promise 理解与使用

    个人觉得这篇博客写的非常详细且易懂,推荐给小伙伴们~ https://www.cnblogs.com/lvdabao/p/es6-promise-1.html#!comments