一、实例创建

  在创建实例时,调用__new__方法和__init__方法,这两个方法在没有定义时,是自动调用了object来实现的。python3默认创建的类是继承了object。

class A(object):
def __init__(self, *args, **kwargs):
self.name, self.age, self.gender = args[:3]
def __new__(cls, *args, **kwargs):
print("__new__ has called.")
return super(A, cls).__new__(cls)
# 可写为 super().__new__(cls) 或 object.__new__(cls) a = A("Li", 27, "male")
print(a.name, a.age, a.gender) """
__new__ has called.
Li 27 male """

二、类的创建

  以class关键字开头的上下文在定义时就已经被解释执行。而函数(包括匿名函数)在没被调用时是不执行的。这个过程本质上做了一件事情:从元类type那里创建了一个名为A的类,开辟类内存空间,并读取class语句的上下文,将类属性和方法写进去。

print("--解释器开始执行--")
def func():
print("what the hell?") print("--开始读取class关键字的上下文--")
class A:
name = "A"
func()
print("--上下文结束--") def fn1():
print("--开始读取匿名函数--")
def fn2():
pass
pass
print("--读取结束--")
print("--解释器执行结束--") """
--解释器开始执行--
--开始读取class关键字的上下文--
what the hell?
--上下文结束--
--解释器执行结束--
"""

  " 使用class语句定义新类时,将会发生很多事情。首先,类主体将为作其自己的私有字典内的一系列语句来执行。其内容里语句的执行与正常代码中的执行过程相同,只是增加了会在私有成员(名称以__开头)上发生的名称变形。然后,类的名称、基类列表和字典将传递给元类的解构函数,以创建相应的类对象。最后,调用元类type(),这里可以自定义。在python3中,使用class Foo(metaclass=type)来显式地指定元类。如果没有找到任何__metaclass__值,Python将使用默认的元类type。"  -- <<python 参考手册(第四版)>>

class_name = "Foo"    # 类名
class_parents = (object, ) # 基类
# 类主体
class_body = """
name = "Foo"
def __init__(self, x):
self.x = x
def hello(self):
print("Hello")
"""
class_dict = {}
# 在局部字典class_dict中执行类主体
exec(class_body, globals(), class_dict)
# 创建类对象Foo
Foo = type(class_name, class_parents, class_dict) # type可以指定
Foo("X").hello()
# Hello

  type类创建类时,指定了类的三个部分: class_name, class_parent, class_dict。这一步是在底层实现的。

string = """name = 'Li'
age = 2712
"""
# 字符串必须是换行符或分号分割
dic = {}
exec(string, globals()) # globals表示执行字符串后的结果保存到全局命名空间中
print(name, age)
print(dic)
exec(string, globals(), dic) # locals表示执行字符串后的结果保存到局部一个映射对象中
print(dic) """
Li 2712
{}
{'name': 'Li', 'age': 2712}
"""

exec函数用法

  我们可以用type动态地创建类。你可以用上面的方式去实现类的上下文,也可以直接定义函数并给到字典里,尽管它看起来有些"污染"全局空间:

class_name = "A"
class_parent = () label = "hello world" def init(self, name, age):
self.name = name
self.age = age
def hello(self):
print("Hello, i'm %s, %s." % (self.name, self.age)) A = type(class_name, class_parent, {"__init__": init, "hello": hello, "label": label}) a = A("Li", 18)
a.hello()
print(a.label) """
Hello, i'm Li, 18.
hello world
"""

三、元类的实现过程

  

复制代码

print("First...")
class MyType(type):
print("MyType begin ...")
def __init__(self, *args, **kwargs):
print("Mytype __init__", self, *args, **kwargs , sep="\r\n", end="\r\n\r\n")
type.__init__(self, *args, **kwargs) # 调用type.__init__ def __call__(self, *args, **kwargs):
print("Mytype __call__", *args, **kwargs)
obj = self.__new__(self) # 第一个self是Foo,第二个self是F("Alex")
print("obj ",obj, *args, **kwargs)
print(self)
self.__init__(obj,*args, **kwargs)
return obj def __new__(cls, *args, **kwargs):
print("Mytype __new__", cls, *args, **kwargs, sep="\r\n", end="\r\n\r\n")
return type.__new__(cls, *args, **kwargs)
print("MyType end ...") print('Second...')
class Foo(metaclass=MyType):
print("begin...")
def __init__(self, name):
self.name = name
print("Foo __init__") def __new__(cls, *args, **kwargs):
print("Foo __new__", end="\r\n\r\n")
return object.__new__(cls)
print("over...") def __call__(self, *args, **kwargs):
print("Foo __call__", self, *args, **kwargs, end="\r\n\r\n") print("third...")
f = Foo("Alex")
print("f",f, end="\r\n\r\n")
f()
print("fname",f.name) """
First...
MyType begin ...
MyType end ...
Second...
begin...
over...
Mytype __new__
<class '__main__.MyType'>
Foo
()
{'__module__': '__main__', '__qualname__': 'Foo', '__init__': <function Foo.__init__ at 0x10ad89268>, '__new__': <function Foo.__new__ at 0x10ad89488>, '__call__': <function Foo.__call__ at 0x10ad86ae8>} Mytype __init__
<class '__main__.Foo'>
Foo
()
{'__module__': '__main__', '__qualname__': 'Foo', '__init__': <function Foo.__init__ at 0x10ad89268>, '__new__': <function Foo.__new__ at 0x10ad89488>, '__call__': <function Foo.__call__ at 0x10ad86ae8>} third...
Mytype __call__ Alex
Foo __new__ obj <__main__.Foo object at 0x10ae2ac88> Alex
<class '__main__.Foo'>
Foo __init__
f <__main__.Foo object at 0x10ae2ac88> Foo __call__ <__main__.Foo object at 0x10ae2ac88> fname Alex """

  假设MyType是type类,type有三个特殊方法__init__、__call__、__new__。

  首先, First请忽略掉吧。假设底层就这样搞了一个type类,它的名字叫MyType。

  其次,Second这一步。解释器发现class和Foo(),会知道要从元类MyType中"实例化"一个类对象。

    它会首先扫描class Foo()的整个上下文,并分成三部分,类名、基类元组,和私有字典。

    然后它会告诉解释器,马上调用MyType(就是Type)类来创建一个名为Foo的类,来开辟内存空间,把这个Foo的私有字典(包括属性和方法)给放进去。

    于是解释器执行了MyType.__new__,并继续执行MyType.__init__。来创建一个名为Foo的类对象。

  再次,Third这一步。

    首先通过Foo()来调用MyType.__call__,来实例化一个Foo类。它相当于Foo = Type()

    然后依次执行Foo.__new__和Foo.__init__,来实例化一个实例对象。

    Foo()相当于: MyType()(),而MyType()就是F。于是,在a = Foo(),实际上执行了MyType()()。前面说过,实例+()会调用所属类的__call__方法,同样地,类 + ()会调用类所属元类(MyType)的__call__方法。

    至此,一个实例就算创建完成了。

四、抽象基类

  抽象基类有两个特点:

    1.规定继承类必须具有抽象基类指定的方法

    2.抽象基类无法实例化

  基于上述两个特点,抽象基类主要用于接口设计

  实现抽象基类可以使用内置的abc模块

import abc
class Human(metaclass=abc.ABCMeta):
@abc.abstractmethod # 规定子类必须有名为introduce的实例方法
def introduce(self):
pass @abc.abstractproperty # 规定子类必须有名为country的装饰器方法
def country(self):
pass @abc.abstractclassmethod # 规定子类必须有名为gender的类方法
def gender(cls):
pass
@abc.abstractstaticmethod # 规定子类必须有名为hello的静态方法
def hello():
pass
class Person(Human):
__country = "China"
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
return "I'm {}, {}.".format(self.name, self.age) @property
def country(self):
return Person.__country @classmethod
def gender(cls):
return "female" @staticmethod
def hello():
print("What the hell?") person = Person("Li", 24)
print(person.introduce())
print(person.country)
print(Person.gender())
person.hello() # I'm Li, 24.
# China
# female
# What the hell?

  collections.abc模块收集了常用的抽象基类。感兴趣的话可以打开collections.abc查看源码。

__all__ = ["Awaitable", "Coroutine",
"AsyncIterable", "AsyncIterator", "AsyncGenerator",
"Hashable", "Iterable", "Iterator", "Generator", "Reversible",
"Sized", "Container", "Callable", "Collection",
"Set", "MutableSet",
"Mapping", "MutableMapping",
"MappingView", "KeysView", "ItemsView", "ValuesView",
"Sequence", "MutableSequence",
"ByteString",
]

python(七):元类与抽象基类的更多相关文章

  1. python 用abc模块构建抽象基类Abstract Base Classes

    见代码: #!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/08/01 16:58 from abc import ABCMet ...

  2. 类,抽象基类,接口类三者间的区别与联系(C++)

    结构上的区别: 普通类:数据+方法+实现 抽象类:数据+方法(一定包含虚方法n>=1)+部分方法的实现 接口类:方法(纯虚方法) http://www.cnblogs.com/Tris-wu/p ...

  3. 【Python】【元编程】【从协议到抽象基类】

    """class Vector2d: typecode = 'd' def __init__(self,x,y): self.__x = float(x) self.__ ...

  4. Python中的对象行为与特殊方法(二)类型检查与抽象基类

    类型检查 创建类的实例时,该实例的类型为类本身: class Foo(object): pass f = Foo() 要测试实例是否属于某个类,可以使用type()内置函数: >>> ...

  5. Python中的抽象基类

    1.说在前头 "抽象基类"这个词可能听着比较"深奥",其实"基类"就是"父类","抽象"就是&quo ...

  6. 流畅python学习笔记:第十一章:抽象基类

    __getitem__实现可迭代对象.要将一个对象变成一个可迭代的对象,通常都要实现__iter__.但是如果没有__iter__的话,实现了__getitem__也可以实现迭代.我们还是用第一章扑克 ...

  7. 流畅的python学习笔记:第十一章:抽象基类

    __getitem__实现可迭代对象.要将一个对象变成一个可迭代的对象,通常都要实现__iter__.但是如果没有__iter__的话,实现了__getitem__也可以实现迭代.我们还是用第一章扑克 ...

  8. 4.6 C++抽象基类和纯虚成员函数

    参考:http://www.weixueyuan.net/view/6376.html 总结: 在C++中,可以通过抽象基类来实现公共接口 纯虚成员函数没有函数体,只有函数声明,在纯虚函数声明结尾加上 ...

  9. c++之——抽象基类

    在一个虚函数的声明语句的分号前加上 =0:就可以将一个虚函数变成纯虚函数,其中,=0只能出现在类内部的虚函数声明语句处.纯虚函数只用声明,而不用定义,其存在就是为了提供接口,含有纯虚函数的类是抽象基类 ...

随机推荐

  1. codeforces796E Exam Cheating

    本文版权归ljh2000和博客园共有,欢迎转载,但须保留此声明,并给出原文链接,谢谢合作. 本文作者:ljh2000 作者博客:http://www.cnblogs.com/ljh2000-jump/ ...

  2. 基于usb4java实现的java下的usb通信

    项目地址:点击打开 使用java开发的好处就是跨平台,基本上java的开发的程序在linux.mac.MS上都可以运行,对应这java的那句经典名言:一次编写,到处运行.这个项目里面有两种包选择,一个 ...

  3. 一些putty的应用设置

    把windows下putty的key转换成linux上使用的rsa key    http://ask.apelearn.com/question/937 putty生成的密钥导入connectbot ...

  4. tensorflow wide deep 介绍

    https://blog.csdn.net/heyc861221/article/details/80131369 https://blog.csdn.net/heyc861221/article/d ...

  5. HTML5如何做横屏适配

    在移动端中我们经常碰到横屏竖屏的问题,那么我们应该如何去判断或者针对横屏.竖屏来写不同的代码呢. 首先在head中加入如下代码: 1 <meta name="viewport" ...

  6. hihocoder1457

    http://hihocoder.com/problemset/problem/1457 找不重复子串的和 topo序搞一搞,用父亲更新儿子节点的val,记得乘上节点数 //#pragma comme ...

  7. uva109求凸包面积,判断点是不是在凸包内

    自己想了一个方法判断点是不是在凸包内,先求出凸包面积,在求由点与凸包上每两个点之间的面积(点已经排好序了),如果两者相等,则点在凸包内,否则不在(时间复杂度可能有点高)但是这题能过 #include& ...

  8. C++复习5.指针数组字符串

    C/C++ 指针.数组和字符串 本次学习指针.数组.字符串.引用的内存映像. 1.指针 指针的本质:可以执行的程序是由指令.数据和地址组成的.当CPU访问内存单元的时候,不论是读取还是写入,首先要把内 ...

  9. 【51nod-1009】数字1的数量

    给定一个十进制正整数N,写下从1开始,到N的所有正数,计算出其中出现所有1的个数.   例如:n = 12,包含了5个1.1,10,12共包含3个1,11包含2个1,总共5个1. Input 输入N( ...

  10. 解决方案:System.InvalidOperationException: 此实现不是 Windows 平台 FIPS 验证的加密算法的一部分。

    System.InvalidOperationException: This implementation is not part of the Windows Platform FIPS valid ...