Python----面向对象---元类介绍

一、储备知识exec

参数1:字符串形式的命令

参数2:全局作用域(字典形式),如果不指定默认就使用globals()

参数3:局部作用域(字典形式),如果不指定默认使用locals()

示例代码如下:

 1 g = {
 2     ‘x‘: 1,
 3     ‘y‘: 2
 4 }
 5
 6 l = {}
 7
 8 exec(‘‘‘
 9 global x, m
10 x = 10
11 m = 100
12
13 z = 3
14 ‘‘‘, g, l)
15
16 print(g)
17 print(l)
18
19 结果为:
20
21 {‘x‘: 10, ‘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.
22 All Rights Reserved.
23
24 Copyright (c) 2000 BeOpen.com.
25 All Rights Reserved.
26
27 Copyright (c) 1995-2001 Corporation for National Research Initiatives.
28 All Rights Reserved.
29
30 Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
31 All Rights Reserved., ‘credits‘:     Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
32     for supporting Python development.  See www.python.org for more information., ‘license‘: See http://www.python.org/3.6/license.html, ‘help‘: Type help() for interactive help, or help(object) for help about object.}, ‘m‘: 100}
33 {‘z‘: 3}

l为局部变量,执行后会增加z的键值对,g为全局变量,x的值会修改为10,m不存在,会添加进g

python中一切皆对象,对象可以怎么用?

1、都可以被引用, x=obj

2、都可以当做函数的参数传入

3、都可以当做函数的返回值

4、都可以当做容器的元素, l = [func, time, obj, 1]

类也是对象,那他是由什么实例化而来的呢:

 1 class Foo:
 2     pass
 3
 4 obj = Foo()
 5 print(type(obj))
 6 print(type(Foo))
 7
 8 结果为:
 9
10 <class ‘__main__.Foo‘>
11 <class ‘type‘>

可见,Foo类是由type类实例化而来,

1 class Bar:
2     pass
3
4
5 print(type(Bar))
6
7 结果为:
8
9 <class ‘type‘>

产生类的类称之为元类,默认所有使用class定义的类,他们的元类是type

定义类的两中方式:

方式一:class

1 class Chinese:  # Chinese = type(...)
2     country = ‘China‘
3
4     def __init__(self, name, age):
5         self.name = name
6         self.age = age
7
8     def talk(self):
9         print(‘%s is talking ‘ % self.name)

方式二:type

定义类的三要素: 类名, 类的基类们, 类的名称空间

 1 class_name = ‘Chinese‘
 2 class_bases = (object, )
 3
 4 class_body = """
 5 country = ‘China‘
 6
 7 def __init__(self, name, age):
 8     self.name = name
 9     self.age = age
10
11 def talk(self):
12     print(‘%s is talking ‘ % self.name)
13 """
14
15 class_dic = {}
16
17 exec(class_body, globals(), class_dic)
18 print(globals())
19 print(class_dic)
20
21 chinese1 = type(class_name, class_bases, class_dic)
22 print(chinese1)
23
24 结果为:
25
26 {‘__name__‘: ‘__main__‘, ‘__doc__‘: None, ‘__package__‘: None, ‘__loader__‘: <_frozen_importlib_external.SourceFileLoader object at 0x0000026F4279D7F0>, ‘__spec__‘: None, ‘__annotations__‘: {}, ‘__builtins__‘: <module ‘builtins‘ (built-in)>, ‘__file__‘: ‘C:/Users/xu516/PycharmProjects/Python全栈开发/第三模块/面向对象编程/26 元类介绍.py‘, ‘__cached__‘: None, ‘class_name‘: ‘Chinese‘, ‘class_bases‘: (<class ‘object‘>,), ‘class_body‘: "\ncountry = ‘China‘\n\ndef __init__(self, name, age):\n    self.name = name\n    self.age = age\n\ndef talk(self):\n    print(‘%s is talking ‘ % self.name)\n", ‘class_dic‘: {‘country‘: ‘China‘, ‘__init__‘: <function __init__ at 0x0000026F42793510>, ‘talk‘: <function talk at 0x0000026F42A1B620>}}
27 {‘country‘: ‘China‘, ‘__init__‘: <function __init__ at 0x0000026F42793510>, ‘talk‘: <function talk at 0x0000026F42A1B620>}
28 <class ‘__main__.Chinese‘>

type实例化生成chinese1类,

1 obj1 = chinese1(‘egon‘, 88)
2 print(obj1, obj1.name, obj1.age)
3
4 结果为:
5
6 <__main__.Chinese object at 0x0000013E2417B518> egon 88

type类实例化生成的chinese1类,

原文地址:https://www.cnblogs.com/xudachen/p/8660167.html

时间: 2024-11-09 17:41:23

Python----面向对象---元类介绍的相关文章

python面向对象--元类

一个类没有声明自己的元类,默认他的元类就是type,除了使用内置元类type,我们也可以通过继承type来自定义元类,然后使用metaclass关键字参数为一个类指定元类 class Foo: def __init__(self): pass f1=Foo()#f1是通过Foo实例化的对象 #print(type(f1)) print(type(Foo)) print(Foo.__dict__) def __init__(self,name,age): self.name=name self.a

面向对象之元类介绍

标签(空格分隔): 元类介绍 元类介绍: 在正式介绍元类之前,大家储备一下知识:exec; exec命令使用 这个命令有三个参数: 1.字符串形式的命令,(把字符串提取出来) 2.全局作用域:(字典形式,如果不指定,默认使用globals()) 3.局部作用域,(字典形式,如果不指定默认locals) g={'x':1, 'y':2} l={} exec(""" global x,m x=10 m=100 z=3 """,g,l) print(g

面向对象之元类介绍(未完待续)

标签(空格分隔): 元类介绍 元类介绍: 在正式介绍元类之前,大家储备一下知识:exec; exec命令使用 这个命令有三个参数: 1.字符串形式的命令,(把字符串提取出来) 2.全局作用域:(字典形式,如果不指定,默认使用globals()) 3.局部作用域,(字典形式,如果不指定默认locals) g={'x':1, 'y':2} l={} exec(""" global x,m x=10 m=100 z=3 """,g,l) print(g

1.元类介绍/2.自定义元类控制类的行为/3.控制类的实例化行为/4.控制类的实例化行为的应用

1.元类介绍 1.储备知识exec()参数1;字符串形式得命令参数2.全局作用域(字典形式),如果不指定默认就使用globals()参数3.局部作用域(字典形式),如果不指定默认就使用locals() 2.python 一切皆对象 ,对象可以怎么用? 2.1. 都可以被引用 x=obj 2.2. 都可以当作函数得参数传入 2.3. 都可以当作函数得返回值 2.4. 都可以当作容器类得元素 li=[func,time] # 类也是对象,Foo=type() 类是属于type() 类 3.什么叫元类

Python面向对象02/类的空间问题

Python面向对象02/类的空间问题 内容大纲 1.从空间角度研究类 2..类与类之间的关系 1.类的空间问题 1.1何处可以添加对象属性 在类的__init__可以添加,在类的方法也可以添加,在类的外部也可以添加 # class Human: # # mind = '有思想的' # # def __init__(self, name, age): # self.name = name # self.age = age # # def eat(self,argv): # # self.hobb

Python全栈之路----面向对象开发----元类介绍

储备知识exec,可以被当作函数来看待. 参数1:字符串形式的命令 参数2:全局作用域(字典形式),如果不指定默认就使用globals() 参数3:局部作用域(字典形式),如果不指定默认就使用locals() g = {'x':1, 'y':2} l = {} exec(''' global x,m x = 10 m = 100 z = 3 ''', g, l) python中一切皆对象,对象可以怎么用? 1.都可以被引用,x = obj 2.都可以当作函数的参数传入 3.都可以当作函数的返回值

Python之元类详解

一.引子 元类属于Python面向对象编程的深层魔法,99%的人都不得要领,一些自以为搞明白元类的人其实也是自圆其说,点到为止,从队元类的控制上来看就破绽百出,逻辑混乱: 二.什么是元类 一切源自于一句话:Python中一切皆为对象.让我们先定义一个类,然后逐步分析 #!/usr/bin/env python # -*- coding: utf-8 -*- class MyTeacher(object): school='john' def __init__(self,name,age): se

Python中元类

一. 前提: python中一切都是对象,要么是类的对象,要么是元类的对象,type元类是自己的对象.继承层次表示为type(元类)-->类(内置和用户自定义的) --> 类的实例. 二.  目的: 创建类时自动改变类,换句话说就是创建类这种东西的东西. 三.  __metaclass__ 可以通过指定__metaclass__来使用用户自定义的元类创建类. class语句解析顺序: class Myclass(object): pass Myclass里面的__metaclass__ --&

python 面向对象和类成员和异常处理

python 面向对象 你把自己想象成一个上帝,你要创造一个星球,首先你要把它揉成一个个球,两个直径就能创造一个球 class star: '''名字(name),赤道直径(equatorial diameter),极直径(polar diameter)''' def __init__(self,name,eqDiameter,poDiameter): self.name=name self.eqDiameter=eqDiameter #赤道直径 self.poDiameter=poDiamet