Python是一门面向对象的语言,因此Python中数字、字符串、列表、集合、字典、函数、类等都是对象。python
利用 type()
来查看Python中的各对象类型git
In [11]: # 数字
In [12]: type(10)
Out[12]: int
In [13]: type(3.1415926)
Out[13]: float
In [14]: # 字符串
In [15]: type('a')
Out[15]: str
In [16]: type("abc")
Out[16]: str
In [17]: # 列表
In [18]: type(list)
Out[18]: type
In [19]: type([])
Out[19]: list
In [20]: # 集合
In [21]: type(set)
Out[21]: type
In [22]: my_set = {1, 2, 3}
In [23]: type(my_set)
Out[23]: set
In [24]: # 字典
In [25]: type(dict)
Out[25]: type
In [26]: my_dict = {'name': 'hui'}
In [27]: type(my_dict)
Out[27]: dict
In [28]: # 函数
In [29]: def func():
...: pass
...:
In [30]: type(func)
Out[30]: function
In [31]: # 类
In [32]: class Foo(object):
...: pass
...:
In [33]: type(Foo)
Out[33]: type
In [34]: f = Foo()
In [35]: type(f)
Out[35]: __main__.Foo
In [36]: # type
In [37]: type(type)
Out[37]: type
复制代码
能够看出程序员
1
是 int类型 的对象abc
是 str类型 的对象list、set、dict
类型func
是 function类型 的对象Foo
建立出来的对象 f
是 Foo
类型,其类自己 Foo
则是 type类型 的对象。type
自己都是type类型的对象类就是拥有相等功能和相同的属性的对象的集合web
在大多数编程语言中,类就是一组用来描述如何生成一个对象的代码段。在 Python 中这一点仍然成立:编程
In [1]: class ObjectCreator(object):
...: pass
...:
In [2]: my_object = ObjectCreator()
In [3]: print(my_object)
<__main__.ObjectCreator object at 0x0000021257B5A248>
复制代码
可是,Python中的类还远不止如此。类一样也是一种对象。是的,没错,就是对象。只要你 使用关键字 class
,Python解释器在执行的时候就会建立一个对象。markdown
下面的代码段:app
>>> class ObjectCreator(object):
… pass
…
复制代码
将在内存中建立一个对象,名字就是 ObjectCreator
。这个 对象(类对象ObjectCreator)拥有建立对象(实例对象)的能力。可是,它的本质仍然是一个对象,因而乎你能够对它作以下的操做:编程语言
以下示例:svg
In [39]: class ObjectCreator(object):
...: pass
...:
In [40]: print(ObjectCreator)
<class '__main__.ObjectCreator'> In [41]:# 看成参数传递
In [41]: def out(obj):
...: print(obj)
...:
In [42]: out(ObjectCreator)
<class '__main__.ObjectCreator'> In [43]: # hasattr 判断一个类是否有某种属性
In [44]: hasattr(ObjectCreator, 'name')
Out[44]: False
In [45]: # 新增类属性
In [46]: ObjectCreator.name = 'hui'
In [47]: hasattr(ObjectCreator, 'name')
Out[47]: True
In [48]: ObjectCreator.name
Out[48]: 'hui'
In [49]: # 将类赋值给变量
In [50]: obj = ObjectCreator
In [51]: obj()
Out[51]: <__main__.ObjectCreator at 0x212596a7248>
In [52]:
复制代码
由于类也是对象,你能够在运行时动态的建立它们,就像其余任何对象同样。首先,你能够在函数中建立类,使用 class
关键字便可。函数
def cls_factory(cls_name):
""" 建立类工厂 :param: cls_name 建立类的名称 """
if cls_name == 'Foo':
class Foo():
pass
return Foo # 返回的是类,不是类的实例
elif cls_name == 'Bar':
class Bar():
pass
return Bar
复制代码
IPython 测验
MyClass = cls_factory('Foo')
In [60]: MyClass
Out[60]: __main__.cls_factory.<locals>.Foo # 函数返回的是类,不是类的实例
In [61]: MyClass()
Out[61]: <__main__.cls_factory.<locals>.Foo at 0x21258b1a9c8>
复制代码
但这还不够动态,由于你仍然须要本身编写整个类的代码。因为类也是对象,因此它们必须是经过什么东西来生成的才对。
当你使用class关键字时,Python解释器自动建立这个对象。但就和Python中的大多数事情同样,Python仍然提供给你手动处理的方法。
type 还有一种彻底不一样的功能,动态的建立类。
type能够接受一个类的描述做为参数,而后返回一个类。(要知道,根据传入参数的不一样,同一个函数拥有两种彻底不一样的用法是一件很傻的事情,但这在Python中是为了保持向后兼容性)
type 能够像这样工做:
type(类名, 由父类名称组成的元组(针对继承的状况,能够为空),包含属性的字典(名称和值))
好比下面的代码:
In [63]: class Test:
...: pass
...:
In [64]: Test()
Out[64]: <__main__.Test at 0x21258b34048>
In [65]:
复制代码
能够手动像这样建立:
In [69]:# 使用type定义类
In [69]: Test2 = type('Test2', (), {})
In [70]: Test2()
Out[70]: <__main__.Test2 at 0x21259665808>
复制代码
咱们使用 Test2
做为类名,而且也能够把它当作一个变量来做为类的引用。类和变量是不一样的,这里没有任何理由把事情弄的复杂。即 type函数 中第1个实参,也能够叫作其余的名字,这个名字表示类的名字
In [71]: UserCls = type('User', (), {})
In [72]: print(UserCls)
<class '__main__.User'> In [73]:
复制代码
使用 help
来测试这2个类
In [74]: # 用 help 查看 Test类
In [75]: help(Test)
Help on class Test in module __main__:
class Test(builtins.object) | Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
In [76]: # 用 help 查看 Test2类
In [77]: help(Test2)
Help on class Test2 in module __main__:
class Test2(builtins.object) | Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
In [78]:
复制代码
type 接受一个字典来为类定义属性,所以
Parent = type('Parent', (), {'name': 'hui'})
复制代码
能够翻译为:
class Parent(object):
name = 'hui'
复制代码
而且能够将 Parent
当成一个普通的类同样使用:
In [79]: Parent = type('Parent', (), {'name': 'hui'})
In [80]: print(Parent)
<class '__main__.Parent'> In [81]: Parent.name
Out[81]: 'hui'
In [82]: p = Parent()
In [83]: p.name
Out[83]: 'hui'
复制代码
固然,你能够继承这个类,代码以下:
class Child1(Parent):
name = 'jack'
sex = '男'
class Child2(Parent):
name = 'mary'
sex = '女'
复制代码
就能够写成:
Child1 = type('Child1', (Parent, ), {'name': 'jack', 'sex': '男'})
In [85]: Child2 = type('Child2', (Parent, ), {'name': 'mary', 'sex': '女'})
In [87]: Child1.name, Child1.sex
Out[87]: ('jack', '男')
In [88]: Child2.name, Child2.sex
Out[88]: ('mary', '女')
复制代码
注意:
最终你会但愿为你的类增长方法。只须要定义一个有着恰当签名的函数并将其做为属性赋值就能够了。
In [89]: Parent = type('Parent', (), {'name': 'hui'})
In [90]: # 定义函数
In [91]: def get_name(self):
...: return self.name
...:
In [92]: Child3 = type('Child3', (Parent, ), {'name': 'blob', 'get_name': get_name})
In [93]: c3 = Child3()
In [94]: c3.name
Out[94]: 'blob'
In [95]: c3.get_name()
Out[95]: 'blob'
复制代码
In [96]: Parent = type('Parent', (), {'name': 'hui'})
In [97]: # 定义静态方法
In [98]: @staticmethod
...: def test_static():
...: print('static method called...')
...:
In [100]: Child4 = type('Child4', (Parent, ), {'name': 'zhangsan', 'test_static': test_static})
In [101]: c4 = Child4()
In [102]: c4.test_static()
static method called...
In [103]: Child4.test_static()
static method called...
复制代码
In [105]: Parent = type('Parent', (), {'name': 'hui'})
In [106]: # 定义类方法
In [107]: @classmethod
...: def test_class(cls):
...: print(cls.name)
...:
In [108]: Child5 = type('Child5', (Parent, ), {'name': 'lisi', 'test_class': test_class})
In [109]: c5 = Child5()
In [110]: c5.test_class()
lisi
In [111]: Child5.test_class()
lisi
复制代码
你能够看到,在Python中,类也是对象,你能够动态的建立类。这就是当你使用关键字 class
时 Python
在幕后作的事情,就是经过元类来实现的。
较为完整的使用 type 建立类的方式:
class Animal(object):
def eat(self):
print('吃东西')
def dog_eat(self):
print('喜欢吃骨头')
def cat_eat(self):
print('喜欢吃鱼')
Dog = type('Dog', (Animal, ), {'tyep': '哺乳类', 'eat': dog_eat})
Cat = type('Cat', (Animal, ), {'tyep': '哺乳类', 'eat': cat_eat})
# ipython 测验
In [125]: animal = Animal()
In [126]: dog = Dog()
In [127]: cat = Cat()
In [128]: animal.eat()
吃东西
In [129]: dog.eat()
喜欢吃骨头
In [130]: cat.eat()
喜欢吃鱼
复制代码
元类就是用来建立类的【东西】。你建立类就是为了建立类的实例对象,不是吗?可是咱们已经学习到了Python中的类也是对象。
元类就是用来建立这些类(对象)的,元类就是类的类,你能够这样理解为:
MyClass = MetaClass() # 使用元类建立出一个对象,这个对象称为“类”
my_object = MyClass() # 使用“类”来建立出实例对象
复制代码
你已经看到了type可让你像这样作:
MyClass = type('MyClass', (), {})
复制代码
这是由于函数 type
其实是一个元类。type
就是 Python在背后用来建立全部类的元类。如今你想知道那为何 type 会所有采用小写形式而不是 Type 呢?好吧,我猜这是为了和 str 保持一致性,str是用来建立字符串对象的类,而 int 是用来建立整数对象的类。type 就是建立类对象的类。你能够经过检查 __class__
属性来看到这一点。所以 Python中万物皆对象
如今,对于任何一个 __class__
的 __class__
属性又是什么呢?
In [136]: a = 10
In [137]: b = 'acb'
In [138]: li = [1, 2, 3]
In [139]: a.__class__.__class__
Out[139]: type
In [140]: b.__class__.__class__
Out[140]: type
In [141]: li.__class__.__class__
Out[141]: type
In [142]: li.__class__.__class__.__class__
Out[142]: type
复制代码
所以,元类就是建立类这种对象的东西。type 就是 Python的内建元类,固然了,你也能够建立本身的元类。
__metaclass__
属性你能够在定义一个类的时候为其添加 __metaclass__
属性。
class Foo(object):
__metaclass__ = something…
...省略...
复制代码
若是你这么作了,Python就会用元类来建立类Foo。当心点,这里面有些技巧。你首先写下 class Foo(object)
,可是类Foo尚未在内存中建立。Python会在类的定义中寻找 __metaclass__
属性,若是找到了,Python就会用它来建立类Foo,若是没有找到,就会用内建的 type
来建立这个类。
class Foo(Bar):
pass
复制代码
Python作了以下的操做:
__metaclass__
这个属性吗?若是有,Python会经过 __metaclass__
建立一个名字为Foo的类(对象)__metaclass__
,它会继续在 Bar(父类) 中寻找 __metaclass__
属性,并尝试作和前面一样的操做。__metaclass__
,它就会在模块层次中去寻找 __metaclass__
,并尝试作一样的操做。__metaclass__
,Python就会用内置的 type
来建立这个类对象。如今的问题就是,你能够在 __metaclass__
中放置些什么代码呢?
答案就是:能够建立一个类的东西。那么什么能够用来建立一个类呢?type,或者任何使用到type或者子类化的type均可以。
元类的主要目的就是为了当建立类时可以自动地改变类。
假想一个很傻的例子,你决定在你的模块里全部的类的属性都应该是大写形式。有好几种方法能够办到,但其中一种就是经过在模块级别设定 __metaclass__
。采用这种方法,这个模块中的全部类都会经过这个元类来建立,咱们只须要告诉元类把全部的属性都改为大写形式就万事大吉了。
幸运的是,__metaclass__
实际上能够被任意调用,它并不须要是一个正式的类。因此,咱们这里就先以一个简单的函数做为例子开始。
# -*- coding:utf-8 -*-
def upper_attr(class_name, class_parents, class_attr):
# class_name 会保存类的名字 Foo
# class_parents 会保存类的父类 object
# class_attr 会以字典的方式保存全部的类属性
# 遍历属性字典,把不是__开头的属性名字变为大写
new_attr = {}
for name, value in class_attr.items():
if not name.startswith("__"):
new_attr[name.upper()] = value
# 调用type来建立一个类
return type(class_name, class_parents, new_attr)
class Foo(object):
__metaclass__ = upper_attr # 设置Foo类的元类为upper_attr
bar = 'bip'
print(hasattr(Foo, 'bar'))
# Flase
print(hasattr(Foo, 'BAR'))
# True
f = Foo()
print(f.BAR)
复制代码
# -*- coding:utf-8 -*-
def upper_attr(class_name, class_parents, class_attr):
#遍历属性字典,把不是__开头的属性名字变为大写
new_attr = {}
for name,value in class_attr.items():
if not name.startswith("__"):
new_attr[name.upper()] = value
#调用type来建立一个类
return type(class_name, class_parents, new_attr)
# 再类的继承()中使用metaclass
class Foo(object, metaclass=upper_attr):
bar = 'bip'
print(hasattr(Foo, 'bar'))
# Flase
print(hasattr(Foo, 'BAR'))
# True
f = Foo()
print(f.BAR)
复制代码
再作一次,这一次用一个真正的 class
来当作元类。
class UpperAttrMetaClass(type):
def __new__(cls, class_name, class_parents, class_attr):
# 遍历属性字典,把不是__开头的属性名字变为大写
new_attr = {}
for name, value in class_attr.items():
if not name.startswith("__"):
new_attr[name.upper()] = value
# 方法1:经过'type'来作类对象的建立
return type(class_name, class_parents, new_attr)
# 方法2:复用type.__new__方法
# 这就是基本的OOP编程,没什么魔法
# return type.__new__(cls, class_name, class_parents, new_attr)
# python3的用法
class Foo(object, metaclass=UpperAttrMetaClass):
bar = 'bip'
# python2的用法
class Foo(object):
__metaclass__ = UpperAttrMetaClass
bar = 'bip'
print(hasattr(Foo, 'bar'))
# 输出: False
print(hasattr(Foo, 'BAR'))
# 输出: True
f = Foo()
print(f.BAR)
# 输出: 'bip'
复制代码
__new__ 是在__init__以前被调用的特殊方法
__new__是用来建立对象并返回之的方法
而__init__只是用来将传入的参数初始化给对象
这里,建立的对象是类,咱们但愿可以自定义它,因此咱们这里改写__new__
复制代码
就是这样,除此以外,关于元类真的没有别的可说的了。但就元类自己而言,它们实际上是很简单的:
如今回到咱们的大主题上来,到底是为何你会去使用这样一种容易出错且晦涩的特性?
好吧,通常来讲,你根本就用不上它:
“元类就是深度的魔法,99%的用户应该根本没必要为此操心。若是你想搞清楚到底是否须要用到元类,那么你就不须要它。那些实际用到元类的人都很是清楚地知道他们须要作什么,并且根本不须要解释为何要用元类。” —— Python界的领袖 Tim Peters
源代码已上传到 Gitee
PythonKnowledge: Python知识宝库,欢迎你们来访。
✍ 码字不易,还望各位大侠多多支持❤️。
新建文件夹X
大天然用数百亿年创造出咱们现实世界,而程序员用几百年创造出一个彻底不一样的虚拟世界。咱们用键盘敲出一砖一瓦,用大脑构建一切。人们把1000视为权威,咱们反其道行之,捍卫1024的地位。咱们不是键盘侠,咱们只是平凡世界中不凡的缔造者 。