您的位置:首页 > 编程语言 > Python开发

[置顶] 4000 关于python创建类的深入理解

2018-01-25 15:45 609 查看

背景

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

class Foo(object):
def __init__(self, name):
self.name = name

f = 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 = name
self.age = age

Foo = 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将会在类定义中寻找 [b]metaclass[/b] .如果找到了就用它来创建类对象 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()] = val
else:
uppercase_attr[name] = val
return 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 = name
print("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 obj

def __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 = name
print("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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: