元类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. 使用MySQL统计页面访问及排名

    统计访问页面数量,以分辨率进行排名 SELECT CONCAT(`height` , '*', `width`) AS `resolution` , COUNT(CONCAT(`height`, '* ...

  2. Handler引起的内存泄露

    一般我都写handler的时候是这样的:   public class MyActivity extends Activity{ private final Handler myHandler = n ...

  3. 版本号比较versioncompare方法,java实现

    测试

  4. How `new’ operator works ?

    这是2013年写的一篇旧文,放在gegahost.net上面 http://raison.gegahost.net/?p=15 February 15, 2013 How `new’ operator ...

  5. mysql踩坑记录之limit和sum函数混合使用问题

    问题复盘本次复盘会用一个很简单的订单表作为示例. 数据准备订单表建表语句如下(这里偷懒了,使用了自增ID,实际开发中不建议使用自增ID作为订单ID) CREATE TABLE `order` ( `i ...

  6. Bug的定义和分类

    什么是BUG 使用人工或自动手段,来运行或测试某个系统的过程.其目的在于检验它是否满足规定的需求或弄清预期结果与实际结果之间的差别 BUG分类 完全没有实现的功能 基本实现了用户需要的功能,但是运行时 ...

  7. linux部署全流程(未完)

    一.环境搭建 1.jdk 2.tomcat 3.nginx 4.redis 推荐工具:winSCP(用来传输文件).SecureCRT(用来执行命令) 1.jdk 下载地址:https://www.o ...

  8. C++:new的使用

    这里先开个头,以后做详细补充个: new 分配内存失败后会返回空指针:

  9. c# xml本地化用法

    1.普通格式 2.占位符格式 注意事项: 1.Pascal命名法 2.key只是key,中间不需要空格,value可以空格 3.占位符左右两边分别空一格

  10. 四、StaticList 和 DynamicList

    1.StaticList类模板 StaticList的设计要点:类模板 使用原生数组作为顺序存储空间 使用模板参数决定数组大小 template <typename T, int N> c ...