元类

元类

1.首先介绍exec

exec:三个参数
参数一:字符串形式的命令
参数二:全局作用域(字典形式),如果不指定,默认为globals()
参数三:局部作用域(字典形式),如果不指定,默认为locals()

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
g={
'x':1,
'y':2
}
l={}

exec('''
global x,z
x=100
z=200

m=300
''',g,l)

print(g) #{'x': 100, 'y': 2,'z':200,......}
print(l) #{'m': 300}

E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
{'x': 100, 'y': 2, '__builtins__': {'__name__': 'builtins', '__doc__': "Built-in functions, exceptions, and other objects.\n\nNoteworthy: None is the `nil' object; Ellipsis represents `...' in slices.", '__package__': '', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': ModuleSpec(name='builtins', loader=<class '_frozen_importlib.BuiltinImporter'>), '__build_class__': <built-in function __build_class__>, '__import__': <built-in function __import__>, 'abs': <built-in function abs>, 'all': <built-in function all>, 'any': <built-in function any>, 'ascii': <built-in function ascii>, 'bin': <built-in function bin>, 'callable': <built-in function callable>, 'chr': <built-in function chr>, 'compile': <built-in function compile>, 'delattr': <built-in function delattr>, 'dir': <built-in function dir>, 'divmod': <built-in function divmod>, 'eval': <built-in function eval>, 'exec': <built-in function exec>, 'format': <built-in function format>, 'getattr': <built-in function getattr>, 'globals': <built-in function globals>, 'hasattr': <built-in function hasattr>, 'hash': <built-in function hash>, 'hex': <built-in function hex>, 'id': <built-in function id>, 'input': <built-in function input>, 'isinstance': <built-in function isinstance>, 'issubclass': <built-in function issubclass>, 'iter': <built-in function iter>, 'len': <built-in function len>, 'locals': <built-in function locals>, 'max': <built-in function max>, 'min': <built-in function min>, 'next': <built-in function next>, 'oct': <built-in function oct>, 'ord': <built-in function ord>, 'pow': <built-in function pow>, 'print': <built-in function print>, 'repr': <built-in function repr>, 'round': <built-in function round>, 'setattr': <built-in function setattr>, 'sorted': <built-in function sorted>, 'sum': <built-in function sum>, 'vars': <built-in function vars>, 'None': None, 'Ellipsis': Ellipsis, 'NotImplemented': NotImplemented, 'False': False, 'True': True, 'bool': <class 'bool'>, 'memoryview': <class 'memoryview'>, 'bytearray': <class 'bytearray'>, 'bytes': <class 'bytes'>, 'classmethod': <class 'classmethod'>, 'complex': <class 'complex'>, 'dict': <class 'dict'>, 'enumerate': <class 'enumerate'>, 'filter': <class 'filter'>, 'float': <class 'float'>, 'frozenset': <class 'frozenset'>, 'property': <class 'property'>, 'int': <class 'int'>, 'list': <class 'list'>, 'map': <class 'map'>, 'object': <class 'object'>, 'range': <class 'range'>, 'reversed': <class 'reversed'>, 'set': <class 'set'>, 'slice': <class 'slice'>, 'staticmethod': <class 'staticmethod'>, 'str': <class 'str'>, 'super': <class 'super'>, 'tuple': <class 'tuple'>, 'type': <class 'type'>, 'zip': <class 'zip'>, '__debug__': True, 'BaseException': <class 'BaseException'>, 'Exception': <class 'Exception'>, 'TypeError': <class 'TypeError'>, 'StopAsyncIteration': <class 'StopAsyncIteration'>, 'StopIteration': <class 'StopIteration'>, 'GeneratorExit': <class 'GeneratorExit'>, 'SystemExit': <class 'SystemExit'>, 'KeyboardInterrupt': <class 'KeyboardInterrupt'>, 'ImportError': <class 'ImportError'>, 'ModuleNotFoundError': <class 'ModuleNotFoundError'>, 'OSError': <class 'OSError'>, 'EnvironmentError': <class 'OSError'>, 'IOError': <class 'OSError'>, 'WindowsError': <class 'OSError'>, 'EOFError': <class 'EOFError'>, 'RuntimeError': <class 'RuntimeError'>, 'RecursionError': <class 'RecursionError'>, 'NotImplementedError': <class 'NotImplementedError'>, 'NameError': <class 'NameError'>, 'UnboundLocalError': <class 'UnboundLocalError'>, 'AttributeError': <class 'AttributeError'>, 'SyntaxError': <class 'SyntaxError'>, 'IndentationError': <class 'IndentationError'>, 'TabError': <class 'TabError'>, 'LookupError': <class 'LookupError'>, 'IndexError': <class 'IndexError'>, 'KeyError': <class 'KeyError'>, 'ValueError': <class 'ValueError'>, 'UnicodeError': <class 'UnicodeError'>, 'UnicodeEncodeError': <class 'UnicodeEncodeError'>, 'UnicodeDecodeError': <class 'UnicodeDecodeError'>, 'UnicodeTranslateError': <class 'UnicodeTranslateError'>, 'AssertionError': <class 'AssertionError'>, 'ArithmeticError': <class 'ArithmeticError'>, 'FloatingPointError': <class 'FloatingPointError'>, 'OverflowError': <class 'OverflowError'>, 'ZeroDivisionError': <class 'ZeroDivisionError'>, 'SystemError': <class 'SystemError'>, 'ReferenceError': <class 'ReferenceError'>, 'BufferError': <class 'BufferError'>, 'MemoryError': <class 'MemoryError'>, 'Warning': <class 'Warning'>, 'UserWarning': <class 'UserWarning'>, 'DeprecationWarning': <class 'DeprecationWarning'>, 'PendingDeprecationWarning': <class 'PendingDeprecationWarning'>, 'SyntaxWarning': <class 'SyntaxWarning'>, 'RuntimeWarning': <class 'RuntimeWarning'>, 'FutureWarning': <class 'FutureWarning'>, 'ImportWarning': <class 'ImportWarning'>, 'UnicodeWarning': <class 'UnicodeWarning'>, 'BytesWarning': <class 'BytesWarning'>, 'ResourceWarning': <class 'ResourceWarning'>, 'ConnectionError': <class 'ConnectionError'>, 'BlockingIOError': <class 'BlockingIOError'>, 'BrokenPipeError': <class 'BrokenPipeError'>, 'ChildProcessError': <class 'ChildProcessError'>, 'ConnectionAbortedError': <class 'ConnectionAbortedError'>, 'ConnectionRefusedError': <class 'ConnectionRefusedError'>, 'ConnectionResetError': <class 'ConnectionResetError'>, 'FileExistsError': <class 'FileExistsError'>, 'FileNotFoundError': <class 'FileNotFoundError'>, 'IsADirectoryError': <class 'IsADirectoryError'>, 'NotADirectoryError': <class 'NotADirectoryError'>, 'InterruptedError': <class 'InterruptedError'>, 'PermissionError': <class 'PermissionError'>, 'ProcessLookupError': <class 'ProcessLookupError'>, 'TimeoutError': <class 'TimeoutError'>, 'open': <built-in function open>, 'quit': Use quit() or Ctrl-Z plus Return to exit, 'exit': Use exit() or Ctrl-Z plus Return to exit, 'copyright': Copyright (c) 2001-2017 Python Software Foundation.
All Rights Reserved.

Copyright (c) 2000 BeOpen.com.
All Rights Reserved.

Copyright (c) 1995-2001 Corporation for National Research Initiatives.
All Rights Reserved.

Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
All Rights Reserved., 'credits':     Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
    for supporting Python development.  See www.python.org for more information., 'license': Type license() to see the full license text, 'help': Type help() for interactive help, or help(object) for help about object.}, 'z': 200}
{'m': 300}

Process finished with exit code 0

2.元类

2.1元类是什么

元类是用于创建类的类,是类的模板
元类是用来控制如何创建类的,正如类是创建对象的模板一样,而元类是为了控制类的创建行为
元类的实例化结果为我们用class定义的类,正如类的实例化是对象(f1对象是Foo类的一个实例,Foo类是type类的一个实例)
type是python的一个内建元类,用来直接控制生成类,Python中任何class定义的类其实都是type类实例化的对象。

2.2type创建类的方式

"方式一:使用class关键字创建的类"
class Chinese(object):
    country='China'
    def __init__(self,name,age):
        self.name=name
        self.age=age
    def talk(self):
        print('%s is talking' %self.name)
"方式二:使用type创建类"
#准备工作:
type(class_name,class_bases,class_dic)
#type创建类主要分为三部分
  1 类名===class_name
  2 类的父类===class_bases
  3 类体===class_dic==即类的内容,可使用exec产生

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
#类名
class_name='Chinese'
#类的父类
class_bases=(object,)
#类体
class_body="""
country='China'
def __init__(self,name,age):
    self.name=name
    self.age=age
def talk(self):
    print('%s is talking' %self.name)
"""
#步骤一(先处理类体->名称空间):类体定义的名字都会存放于类的名称空间中(一个局部的名称空间),
# 我们可以事先定义一个空字典,
# 然后用exec去执行类体的代码(exec产生名称空间的过程与真正的class过程类似,只是后者会将__开头的属性变形),
# 生成类的局部名称空间,即填充字典
class_dic={}
exec(class_body,globals(),class_dic)
print("class_dic===",class_dic)
# 步骤二:调用元类type(也可以自定义)来产生类Chinense
Foo=type(class_name,class_bases,class_dic) #实例化type得到对象Foo,即我们用class定义的类Foo

print(Foo)
print(type(Foo))
print(isinstance(Foo,type))
print(Foo.__dict__)

E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
class_dic=== {'country': 'China', '__init__': <function __init__ at 0x00000204CBF63E18>, 'talk': <function talk at 0x00000204CC141C80>}
<class '__main__.Chinese'>
<class 'type'>
True
{'country': 'China', '__init__': <function __init__ at 0x000001DDF5A33E18>, 'talk': <function talk at 0x000001DDF5C11C80>, '__module__': '__main__', '__dict__': <attribute '__dict__' of 'Chinese' objects>, '__weakref__': <attribute '__weakref__' of 'Chinese' objects>, '__doc__': None}

Process finished with exit code 0

2.3自定义元类,控制类的行为

一个类没有声明自己的元类,默认他的元类就是type,除了使用元类type,用户也可以通过继承type来自定义元类

"定义类的时候,就会自动运行Mymeta了"
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
class Mymeta(type):
    def __init__(self,class_name,class_bases,class_dic):
        print("metadata") #验证定义类的时候就运行了该类
        if not class_name.istitle():
            raise TypeError('类名的首字母必须大写')

        if '__doc__' not in class_dic or not class_dic['__doc__'].strip():
            raise TypeError('必须有注释,且注释不能为空')

        super(Mymeta,self).__init__(class_name,class_bases,class_dic)

class Chinese(object,metaclass=Mymeta):
    '''
    中文人的类
    '''
    country='China'

    def __init__(self,namem,age):
        self.name=namem
        self.age=age

    def talk(self):
        print('%s is talking' %self.name)

E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
metadata

Process finished with exit code 0
"类名改为小写,运行"
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
class Mymeta(type):
    def __init__(self,class_name,class_bases,class_dic):
        print("metadata")
        if not class_name.istitle():
            raise TypeError('类名的首字母必须大写')

        if '__doc__' not in class_dic or not class_dic['__doc__'].strip():
            raise TypeError('必须有注释,且注释不能为空')

        super(Mymeta,self).__init__(class_name,class_bases,class_dic)

class chinese(object,metaclass=Mymeta):
    '''
    中文人的类
    '''
    country='China'

    def __init__(self,namem,age):
        self.name=namem
        self.age=age

    def talk(self):
        print('%s is talking' %self.name)

E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
metadata
Traceback (most recent call last):
  File "E:/PythonProject/python-test/BasicGrammer/test.py", line 15, in <module>
    class chinese(object,metaclass=Mymeta):
  File "E:/PythonProject/python-test/BasicGrammer/test.py", line 8, in __init__
    raise TypeError('类名的首字母必须大写')
TypeError: 类名的首字母必须大写

Process finished with exit code 1
"验证没有注释时的情况"
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
class Mymeta(type):
    def __init__(self,class_name,class_bases,class_dic):
        print("metadata")
        if not class_name.istitle():
            raise TypeError('类名的首字母必须大写')

        if '__doc__' not in class_dic or not class_dic['__doc__'].strip():
            raise TypeError('必须有注释,且注释不能为空')

        super(Mymeta,self).__init__(class_name,class_bases,class_dic)

class Chinese(object,metaclass=Mymeta):

    country='China'

    def __init__(self,namem,age):
        self.name=namem
        self.age=age

    def talk(self):
        print('%s is talking' %self.name)

E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
metadata
Traceback (most recent call last):
  File "E:/PythonProject/python-test/BasicGrammer/test.py", line 15, in <module>
    class Chinese(object,metaclass=Mymeta):
  File "E:/PythonProject/python-test/BasicGrammer/test.py", line 11, in __init__
    raise TypeError('必须有注释,且注释不能为空')
TypeError: 必须有注释,且注释不能为空

Process finished with exit code 1

2.4自定义元类控制类的实例化行为

"调用obj对象时,调用__call__方法"
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
#知识储备__call__方法
class Foo:
    var = "var"
    def __call__(self, *args, **kwargs):
        print(self)
        print(args)
        print(kwargs)

obj=Foo()
# print(obj.var) 这样不会调用__call__
#调用obj对象时,调用__call__方法
obj(1,2,3,a=1,b=2,c=3) #obj.__call__(obj,1,2,3,a=1,b=2,c=3)

#元类内部也应有有一个__call__方法,会在调用Foo时触发执行
#Foo(1,2,x=1)  #Foo.__call__(Foo,1,2,x=1)
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
class Mymeta(type):
    def __init__(self,class_name,class_bases,class_dic):
        if not class_name.istitle():
            raise TypeError('类名的首字母必须大写')

        if '__doc__' not in class_dic or not class_dic['__doc__'].strip():
            raise TypeError('必须有注释,且注释不能为空')

        super(Mymeta,self).__init__(class_name,class_bases,class_dic)

    def __call__(self, *args, **kwargs): #obj=Chinese('egon',age=18)
        print("exec __call__")

        #第一件事:先造一个空对象obj
        obj=object.__new__(self)
        #第二件事:初始化obj
        self.__init__(obj,*args,**kwargs)
        #第三件事:返回obj
        return obj

class Chinese(object,metaclass=Mymeta):
    '''
    中文人的类
    '''
    country='China'

    def __init__(self,namem,age):
        self.name=namem
        self.age=age

    def talk(self):
        print('%s is talking' %self.name)

obj=Chinese('egon',age=18) #Chinese.__call__(Chinese,'egon',18)

print(obj.__dict__)

E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
exec __call__
{'name': 'egon', 'age': 18}

Process finished with exit code 0

2.5自定义元类控制类的实例化行为的应用

"#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
#单例模式
#实现方式一:
class MySQL:
    __instance=None #__instance=obj1

    def __init__(self):
        self.host='127.0.0.1'
        self.port=3306

    @classmethod
    def singleton(cls):
        if not cls.__instance:
            obj=cls()
            cls.__instance=obj
        return cls.__instance

#三个对象都是一个,因为只创建了一次
obj1=MySQL.singleton()
obj2=MySQL.singleton()
obj3=MySQL.singleton()

print(obj1 is obj2 is obj3)
"

E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
True

Process finished with exit code 0
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
#单例模式
#实现方式二:元类的方式
class Mymeta(type):
    def __init__(self,class_name,class_bases,class_dic):
        if not class_name.istitle():
            raise TypeError('类名的首字母必须大写')

        if '__doc__' not in class_dic or not class_dic['__doc__'].strip():
            raise TypeError('必须有注释,且注释不能为空')

        super(Mymeta,self).__init__(class_name,class_bases,class_dic)
        self.__instance=None

    def __call__(self, *args, **kwargs): #obj=Chinese('egon',age=18)
        if not self.__instance:
            obj=object.__new__(self)
            self.__init__(obj)
            self.__instance=obj

        return self.__instance

class Mysql(object,metaclass=Mymeta):
    '''
    mysql xxx
    '''
    def __init__(self):
        self.host='127.0.0.1'
        self.port=3306

obj1=Mysql()
obj2=Mysql()
obj3=Mysql()

print(obj1 is obj2 is obj3)

E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
True

Process finished with exit code 0

转载于:https://blog.51cto.com/10983441/2393952

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/100925.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • Vue生成二维码_vue通过二维码分享

    Vue生成二维码_vue通过二维码分享转存vue生成二维码并下载1、下载插件npminstall–saveqrcodejs22、引入constQRCode=require(“qrcodejs2″)3、组件使用<template><divclass=”qr_code”><divstyle=”display:flex;align-items:center”>地址:<Inputid=”text”type=”te

  • arcgis附图制作_怎么制作图片的浮雕效果

    arcgis附图制作_怎么制作图片的浮雕效果ArcGIS制作地图时可以制作出很多很炫的效果,比如地图阴影、地图晕渲效果、浮雕效果、三维效果等等。本实验讲解在ArcGIS中制作浮雕效果地图,效果如下所示:1.加载矢量数据加载实验数据包data44.rar中的秦安县乡镇矢量数据:2.缓冲区分析点击【地理处理】下拉菜单,点击【缓冲区】。输入要素选择秦安县乡镇数据,选择输出要素路径,线性单位输入-0.4,单位为千米,侧类型选择两侧,融合类型选择ALL,点击确定。缓冲区效果:3.欧氏距离分析欧氏距离工具用于计算每个像元到最近.

  • cholesky分解_java toarray方法

    cholesky分解_java toarray方法接着LU分解继续往下,就会发展出很多相关但是并不完全一样的矩阵分解,最后对于对称正定矩阵,我们则可以给出非常有用的cholesky分解。这些分解的来源就在于矩阵本身存在的特殊的结构。对于矩阵A,如果没有任何的特殊结构,那么可以给出A=L*U分解,其中L是下三角矩阵且对角线全部为1,U是上三角矩阵但是对角线的值任意,将U正规化成对角线为1的矩阵,产生分解A=L*D*U,D为对角矩阵。如果A为对…

    2022年10月24日
  • Kong插件开发向导

    Kong插件开发向导转载李亚飞大佬的文章:https://www.lyafei.com/简介前面洋洋洒洒写了那么多文章,Kong搭建、Konga搭建、Kong插件开发工具包、Lua算法实现等等,就为了这篇Kong插件开发铺垫,在进一步讨论之前,有必要再简要阐述下Kong是如何构建的,特别是它如何与Nginx集成,以及它与Lua脚本之间的关系。使用lua-nginx-module模块可以在Nginx中启用Lua脚本功能,Kong与OpenResty一起发布,OpenResty中已经包.

  • goland 2021 激活码破解方法

    goland 2021 激活码破解方法,https://javaforall.cn/100143.html。详细ieda激活码不妨到全栈程序员必看教程网一起来了解一下吧!

  • 安装tcping

    安装tcpingcping在windows和linux系统中都不是内建的命令,需要我们自己去下载下载命令wgethttps://sources.voidlinux.eu/tcping-1.3.5/tcping-1.3.5.tar.gzsudoyuminstallepel-releaseyuminstalltcpingtcpingwww.baidu.com443详细见图…

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号