背景

我们知道在python中一切皆为对象的概念,那我们们来看一段程序

class Foo(object):def __init__(self, name):self.name = namef = Foo("sty")
print(type(f))
print(type(Foo))#output:
# <class '__main__.Foo'>
# <class 'type'>

如果按照一切事物都是对象的理论:f对象是通过执行Foo类的构造方法创建,那么Foo类对象应该也是通过执行某个类的 构造方法 创建.
通过打印我们可以知道:f对象是Foo类的一个实例,Foo类对象是 type 类的一个实例,即:Foo类对象 是通过type类的构造方法创建。

创建类的深入

那么我们可以知道将可以有两种方法来在python中创建类了
普通方法

class Foo(object):def talk(self):print 'hello sty'f = Foo()
f.talk()

特殊方式

def func(self):print('hello sty')Foo = type('Foo', (object,), {'talk': func}) #创建Foo类f = Foo()
f.talk()
#type第一个参数:类名
#type第二个参数:当前类的基类
#type第三个参数:类的成员

上面的第一种方法是我们常用而且熟悉的,而第二种方法也和第一种方法有着同样的效果。
我们还可以在第二种方法的基础上加上构造函数:

def func(self):print('hello %s' % self.name)def __init__(self, name, age):self.name = nameself.age = ageFoo = type('Foo', (object,), {'talk': func, '__init__': __init__})f = Foo("jack", 22)
f.talk()
#output:
#hello jack

所以我们可以得到一个结论:类默认是由 type 类实例化产生的
你可以看到, 在Python中, 类也是对象, 你可以动态的创建类。 这就是当你使用关键字class时Python在幕后做的事情, 而这就是通过元类来实现的。

什么是元类?

元类就是创建类的东西.
你是为了创建对象才定义类的,对吧?
但是我们已经知道了Python的类是对象.
这里,元类创建类.它们是类的类,你可以把它们想象成这样:

MyClass = MetaClass()
MyObject = MyClass()

我们可以通过type来实现这样的效果:

MyClass = type('MyClass', (), {})

这是因为 type 就是一个元类. type 是Python中创建所有类的元类
现在你可能纳闷为啥子 type 用小写而不写成 Type ?
我想是因为要跟 str 保持一致, str 创建字符串对象, int 创建整数对象. type 正好创建类对象.
你可以通过检查 class 属性来看到这一点.
Python中所有的东西都是对象.包括整数,字符串,函数还有类.所有这些都是对象.所有这些也都是从类中创建
的:

>>> age = 35
>>> age.__class__
<type 'int'>
>>> name = 'bob'
>>> name.__class__
<type 'str'>
>>> def foo(): pass
>>> foo.__class__
<type 'function'>
>>> class Bar(object): pass
>>> b = Bar()
>>> b.__class__
<class '__main__.Bar'>

那么,classclass属性是什么?

>>> age.__class__.__class__
<type 'type'>
>>> name.__class__.__class__
<type 'type'>
>>> foo.__class__.__class__
<type 'type'>
>>> b.__class__.__class__
<type 'type'>

所以,元类就是创建类对象的东西.
如果你愿意你也可以把它叫做’类工厂’. type 是Python的内建元类,当然,你也可以创建你自己的元类

那么问题来了
类默认是由 type 类实例化产生,type类中如何实现的创建类?类又是如何创建对象?
答:类中有一个属性 metaclass,其用来表示该类由 谁 来实例化创建,所以,我们可以为 metaclass 设置一个type类的派生类,从而查看 类 创建的过程。

metaclass属性

当你创建一个函数的时候,你可以添加 metaclass 属性:

class Foo(object):__metaclass__ = something...

如果这么做了,python就会用元类来创建类Foo
你首先写下 class Foo(object), 但是类对象 Foo 还没有在内存中创建.
Python将会在类定义中寻找 metaclass .如果找到了就用它来创建类对象 Foo .如果没找到,就会默认
用 type 创建类.
把下面这段话反复读几次。
当你写下如下代码时候:

class Foo(Bar):pass

Python将会这样运行:
在 Foo 中有没有 _metaclass_ 属性?
如果有,Python会在内存中通过 metaclass 创建一个名字为 Foo 的类对象(我说的是类对象,跟紧我的思
路).
如果Python没有找到 metaclass , 它会继续在Bar(父类) 中寻找 metaclass属性 , 并尝试做和前面
同样的操作.
如果Python在任何父类中都找不到 metaclass , 它就会在模块层次中去寻找 metaclass , 并尝试做
同样的操作。
如果还是找不到 metaclass ,Python就会用内置的 type 来创建这个类对象。
现在的问题就是, 你可以在 metaclass 中放置些什么代码呢?
答案就是:可以创建一个类的东西。
那么什么可以用来创建一个类呢? type , 或者任何使用到 type 或者子类化 type 的东东都可以。
自定义元类
元类的主要目的就是为了当创建类时能够自动地改变类.
通常, 你会为API做这样的事情, 你希望可以创建符合当前上下文的类.
假想一个很傻的例子, 你决定在你的模块里所有的类的属性都应该是大写形式。 有好几种方法可以办到,
但其中一种就是通过在模块级别设定 metaclass .
采用这种方法, 这个模块中的所有类都会通过这个元类来创建, 我们只需要告诉元类把所有的属性都改成
大写形式就万事大吉了。

def upper_attr(future_class_name, future_class_parents, future_class_attr):uppercase_attr = {}for name, val in future_class_attr.items():if not name.startswith('__'):uppercase_attr[name.upper()] = valelse:uppercase_attr[name] = valreturn type(future_class_name, future_class_parents, uppercase_attr)# __metaclass__ = upper_attr# class Foo():
#     bar1 = 'bip'
class Foo(object, metaclass=upper_attr):bar='bip'# False
print(hasattr(Foo, 'bar'))# True
print(hasattr(Foo, 'BAR'))f = Foo()
# bip
print(f.BAR)

继续深入

先来看一段代码,我们来了解一下__new__

class Foo(object):def __init__(self,name):self.name = nameprint("Foo __init__")def __new__(cls, *args, **kwargs):print("Foo __new__",cls, *args, **kwargs)return object.__new__(cls)    #继承父亲的__new__方法,如果注释改行,类没法实例化f = Foo("Alex")
print("f",f)
print("fname",f.name)# output
# Foo __new__ <class '__main__.Foo'> sty
# Foo __init__
# f <__main__.Foo object at 0x000001EF9AB7B518>
# fname sty

我们可以知道__new__是在__init__之前执行的,并且我们在把

return object.__new__(cls) 

注释掉之后,类是没办法实例化的,所以我们可以知道,类其实是通过__new__来实例化的,并且是在__new__中调用的__init__,所以在实例化的时候是先执行的__new__,然后再执行的__init__,一般情况下是不用写的,父类是有的。

再看段代码,了解下__call__的执行顺序:

class MyType(type):def __init__(self,*args,**kwargs):print("Mytype __init__",*args,**kwargs)def __call__(self, *args, **kwargs):print("Mytype __call__", *args, **kwargs)obj = self.__new__(self)print("obj ",obj,*args, **kwargs)print(self)self.__init__(obj,*args, **kwargs)return objdef __new__(cls, *args, **kwargs):print("Mytype __new__",*args,**kwargs)return type.__new__(cls, *args, **kwargs)print('here...')
class Foo(object, metaclass = MyType):def __init__(self,name):self.name = nameprint("Foo __init__")def __new__(cls, *args, **kwargs):print("Foo __new__",cls, *args, **kwargs)return object.__new__(cls)    #如果注释改行,类没法实例化f = Foo("sty")
print("f",f)
print("fname",f.name)#output:
#here...
# Mytype __new__ Foo (<class 'object'>,) {'__module__': '__main__', '__qualname__': 'Foo', '__init__': <function Foo.__init__ at 0x0000014DBE6A4950>, '__new__': <function Foo.__new__ at 0x0000014DBE6A49D8>}
# Mytype __init__ Foo (<class 'object'>,) {'__module__': '__main__', '__qualname__': 'Foo', '__init__': <function Foo.__init__ at 0x0000014DBE6A4950>, '__new__': <function Foo.__new__ at 0x0000014DBE6A49D8>}
# Mytype __call__ sty
# Foo __new__ <class '__main__.Foo'>
# obj  <__main__.Foo object at 0x0000014DBE6BB5C0> sty
# <class '__main__.Foo'>
# Foo __init__
# f <__main__.Foo object at 0x0000014DBE6BB5C0>
# fname sty

通过执行结果我们可以知道:
类的生成 调用 顺序依次是 __new__ --> __init__ --> __call__

结语

这有什么卵用?
大多数情况下是没什么卵用的,

“元类就是深度的魔法, 99%的用户应该根本不必为此操心。 如果你想搞清楚究竟是否需要用到元类, 那么你就不需要它。
那些实际用到元类的人都非常清楚地知道他们需要做什么, 而且根本不需要解释 为什么要用元类。 ” —— Python界的领袖 Tim Peters

元类的主要用途是创建API。 一个典型的例子是Django ORM。

如果想更加深入的了解:
可以查看:
https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python#

参考文献

https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python#
http://www.cnblogs.com/alex3714/articles/5213184.html

转载请注明出处:
CSDN:楼上小宇_home:http://blog.csdn.net/sty945
简书:楼上小宇:http://www.jianshu.com/u/1621b29625df

关于python创建类的深入理解相关推荐

  1. python创建类统计属性_轻松创建统计数据的Python包

    python创建类统计属性 介绍 (Introduction) Sometimes you may need a distribution figure for your slide or class ...

  2. Python 创建类的成员并访问

    类的成员: python 中类的成员是有实例方法和数据成员组成 1 创建实例方法并访问 创建实例方法,就是创类类的时候实例化方法,具体的如下 class People:def __init__(sel ...

  3. python创建类的实例方法-Python中动态创建类实例的方法

    简介 在Java中我们可以通过反射来根据类名创建类实例,那么在Python我们怎么实现类似功能呢? 其实在Python有一个builtin函数import,我们可以使用这个函数来在运行时动态加载一些模 ...

  4. python创建类的实例化_在C中实例化python类#

    IronPython类不是.NET类.它们是IronPython.Runtime.Types.pythotype的实例,后者是Python元类.这是因为Python类是动态的,并且支持在运行时添加和删 ...

  5. 理解python的类实例化_理解python的类实例化

    让我们以一个Foo类开始: class Foo(object): def __init__(self, x, y=0): self.x = x self.y = y 当你实例化它(即创建该类的一个新的 ...

  6. python 创建类_python 用type()创建类

    type()可以查看一个类型,也可以查看变量的类型 class Hello1(object): def hello(self, name = 'world'): print('Hello, %s' % ...

  7. python创建类和类方法

    创建一个类的三种方法: class Annimao():pass class Annimao(object):pass class Annimao:pass 三种类方法: 1.实例方法 class P ...

  8. python创建类的两个对象_Python为一个类创建多个对象

    分步教程 要读取文件内容,请使用io.open.如果任何名称有强调字符,请不要忘记指定文件编码.在with io.open('students.txt', mode="r", en ...

  9. Python创建推导式,理解推导式【详细】

最新文章

  1. android getdecorview 出现空指针,android – 为什么我从TabWidget得到一个空指针异常?...
  2. 用VC写Assembly代码(5) --函数调用(二)
  3. Netty学习总结(4)——图解Netty之Pipeline、channel、Context之间的数据流向
  4. idea插件Iedis 2安装与使用
  5. 做系统ghost步骤图解_两台电脑硬盘对拷图解
  6. poj 1719 Shooting Contest 二分匹配
  7. ubuntu 系统网络突然网络已禁用
  8. 极大似然估计与贝叶斯估计的比较
  9. 小提琴统计图_(翻)云(覆)雨图-小提琴图,密度图、箱线图组合
  10. 在IIS上部署ASP网站
  11. 前端开发3年计划,前端应届生如何做一个职业规划
  12. 不知原谅什么,诚觉世事尽可原谅
  13. 发邮件怎么把附件内容直接显示_优德分享:如何发邮件会让人觉得你更靠谱?...
  14. Latex / Katex 编辑基础化学方程式 点这篇绝对有用
  15. 电脑故障一查通 软件教学
  16. 我的Go+语言初体验——GO+的下载与安装
  17. 如何判断远端主机UDP端口是否开启
  18. 【电子学会】2019年09月图形化三级 -- 猫咪抓老鼠游戏
  19. 景联文科技:为自动驾驶车载语音识别技术提供全方面的数据支持
  20. BZOJ 1022 anti-SG SJ定理

热门文章

  1. Java Calendar.add()方法的使用,参数含义。指定时间差。
  2. springboot整合swagger2之最佳实践
  3. Python 中的魔术方法(双下划线开头和结尾的方法)
  4. 2022-2028中国空中互联网系统市场现状及未来发展趋势报告
  5. Kali2021.2 VMware最新版安装步骤
  6. 自己动手实现20G中文预训练语言模型示例
  7. 数学上各种空间概念的关系图
  8. 深入理解BP神经网络的细节
  9. LeetCode简单题之按奇偶排序数组 II
  10. 基于OpenSeq2Seq的NLP与语音识别混合精度训练