您好,登錄后才能下訂單哦!
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
元類是用于創建類的類,是類的模板
元類是用來控制如何創建類的,正如類是創建對象的模板一樣,而元類是為了控制類的創建行為
元類的實例化結果為我們用class定義的類,正如類的實例化是對象(f1對象是Foo類的一個實例,Foo類是type類的一個實例)
type是python的一個內建元類,用來直接控制生成類,Python中任何class定義的類其實都是type類實例化的對象。
"方式一:使用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
一個類沒有聲明自己的元類,默認他的元類就是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
"調用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
"#!/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
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。