python学习汇总42: types汇总(比较全tcy)

通过例程你能看到python的内置类型和types对应的类型。

本文文档是汇总。例程是新编写,稍微多,耐心看。

types模块                                          发布日期 2018/6/14 
                                                   修改日期 2018/11/17


    https://docs.python.org/3/library/types.html#module-types



-------------------------------------------------------------------------------

1.动态类型创建

    types.new_class(name,bases =(),kwds = None,exec_body = None )

    types.prepare_class(name,bases =(),kwds = None )

        计算适当的元类并创建类命名空间.

    types.resolve_bases(基地)

        按照指定动态解析MRO条目 PEP 560.

-------------------------------------------------------------------------------

2.标准解释器类型

    名称的典型用途是用于isinstance()或 issubclass()检查.



    types.FunctionType=class function(object)

    types.LambdaType       =class function(object)

        lambda 表达式创建用户定义函数和函数的类型 .

    types.GeneratorType    = class generator(object)

        生成器 -iterator对象类型,由生成器函数创建.

    types.CoroutineType      =class coroutine(object)

        由函数创建协程对象类型

    types.AsyncGeneratorType =class async_generator(object

        由异步生成器函数创建的异步生成器 --iterator对象的类型.

    types.CodeType          =class code(object)

        代码对象的类型,如返回的compile().

    types.MethodType        =class method(object)

        用户定义类实例方法类型.

    types.BuiltinFunctionType =class builtin_function_or_method(object)

        内置函数的类型

    types.BuiltinMethodType  =class builtin_function_or_method(object)

        内置类的方法

    types.WrapperDescriptorType=class wrapper_descriptor(object)

        一些内置数据类型和基类方法类型,如 object.__init__()或object.__lt__().

    types.MethodWrapperType= class method-wrapper(object)

        一些内置数据类型和基类绑定方法类型.如,它的类型object().__str__.

        某些内置数据类型的方法类型如str.join().

    types.ClassMethodDescriptorType= class classmethod_descriptor(object)

        某些内置数据类型未绑定类方法类型,例如 dict.__dict__['fromkeys'].

    types.ModuleType(name,doc  None )=class module(object)

        模块的类型.构造函数采用要创建的模块的名称以及可选的文档字符串.

    types.MemberDescriptorType=class member_descriptor(object)

        扩展模块中定义对象类型PyMemberDef,如datetime.timedelta.days.

        此类型用作使用标准转换函数的简单C数据成员的描述符

    types.MappingProxyType(映射)=class mappingproxy(object)

        映射的只读代理.

    types.FrameType  =class frame(object)

    types.GetSetDescriptorType  =class getset_descriptor(object)

    types.TracebackType =class traceback(object)

------------------------------------------------------------------------------

class types.MappingProxyType(映射)

    用途:

        映射的只读代理.

    方法:

        key in proxy

            True如果底层映射具有密钥, 则返回False.

        proxy[key]

            使用键键返回基础映射的项目.引发 KeyErrorif 键不在底层映射中.

        iter(proxy)

            在底层映射的键上返回一个迭代器.这是一个捷径iter(proxy.keys()).

        len(proxy)  返回基础映射中的项目数.

        copy()   返回底层映射的浅表副本.

        get(键[,默认] )

            如果key在底层映射中,则返回key的值,否则返回 default.

            如果未给出default,则默认为,因此此方法永远不会引发a .NoneKeyError

        items() 返回底层映射项( 对)的新视图.(key, value)

        keys()  返回底层映射键的新视图.

        values() 返回底层映射值的新视图.



------------------------------------------------------------------------------

3.其他实用程序类和函数

    class types.SimpleNamespace

        一个简单的object子类,提供对其命名空间的属性访问,以及有意义的repr.

    class types.DynamicClassAttribute(fget = None,fset = None,fdel = None,doc = None )

        将类的属性访问路由到__getattr__.

------------------------------------------------------------------------------

4.协程实用功能

    class types.coroutine(gen_func )

        此函数将生成器函数转换为协程函数.基于生成器的协程仍然是生成器迭代器,

        被认为是协程对象并且是 等待的.但是,它可能不一定实现该__await__()方法.

        

        如果gen_func是生成器函数,它将被就地修改.

        如果gen_func不是生成器函数,它将被包装.如它返回一个实例collections.abc.Generator

        ,则实例将包装在一个等待的代理对象中.所有其他类型的对象将按原样返回.

-------------------------------------------------------------------------------

MethodType   

类实例添加新方法:

用途:类实例添加新方法

说明:不能绑定类方法如下例中add函数
     实例绑定仅仅作用于该实例,类绑定作用于该类名,严格意义上讲不叫类绑定,应称为绑定到实例'student',
     且'student'应该是student类;不同于类方法。
总结:实例方法绑定,仅仅作用于该实例。
from types import MethodType
 
class student(object):
    pass
 
def set_age(self,age):
    self.age = age
    print('self.age=',self.age)

def set_name(self,name):
    self.name = name
    print('self.name=', self.name)
def set_school(self,school):
    self.school = school
    print('self.school=',self.school)

def add(x,y):
     print('x+y=',x+y)
     return x+y  
#测试 


s1 = student()
s2 = student()

s1.set_name = MethodType(set_name, s1)#实例绑定 推荐用法

student.set_school = MethodType(set_school, student)#类名绑定一般不用这样用,易和类方法混淆。
student.set_age = MethodType(set_age,student)

 
s1.set_name("Tom")
s1.set_school("人民大学")
s1.set_age(10)
# s2.age(20) #错误

# student.set_name("Tom")#错误
student.set_school("人民大学")
student.set_age(10) 
# print(student.name) #错误
print(s1.name,s1.age,s1.school,student.age,student.school)

输出:
# self.name= Tom
# self.school= 人民大学
# self.age= 10
# self.school= 人民大学
# self.age= 10
# Tom 10 人民大学 10 人民大学  
types.MappingProxyType()不可变映射类型,(字典)
如果给这个类一个映射, 它会返回一个只对映射视图.虽然是个只读的视图, 但是它是动态的, 这意味着如果对原映射做出了改动,
我们可以通过这个视图观察到, 但是无法通过这个视图对原映射做出修改


# 示例
from types import MappingProxyType

d = {'a': 'b'}

a_view = MappingProxyType(d)# 创建index_a的映射视图
print(a_view)
a_view['a']  #不能对a_view视图进行修改
 

d['b'] = 'bb' # 但是可以对原映射进行修改
print(a_view)

输出:
#{'a': 'b'}
#{'a': 'b', 'b': 'bb'}

 

第二部分:例程

# python3.7 2018/8/21#查看类的属性方法 types.example

import types

class A():
"""
class A def..."""
a_x = -1000

def __init__(self,a_id,a_name):

self.a_id=a_id
self.a_name=a_name

def setx(self, a_id):
self.a_id = a_id

def getx(self):
return self.a_id

@staticmethod # 静态方法
def a_show_static():
print('静态方法:无法访问a_x,a_id和a_name')

@classmethod
def a_show_cls(cls):
return (cls.a_x + 100)

def show(self, x):
print('a show =',self.a_id, x)

class AA(A):
"""class AA def.base is A..."""
x = 11

def __init__(self, id1, name1):
super(AA, self).__init__(a_id=-11, a_name='Tom1')
self.id1 = id1
self.name1 = name1

def setx(self, id1):
self.id1 = id1

def getx(self):
return self.id1

@staticmethod # 静态方法
def static_show():
print('静态方法:无法访问id1和name1')

@classmethod
def cls_show(cls):
return (cls.x + 1000)

def show(self, x):
print('a show =', self.a_id, x)

# -----------------------------------------------------------------------------------------------------
class view_types():
"""查看对象属性方法函数"""
 

   def __init__(self):        
       self.type_base = [            
           'bool', 'int', 'float', 'complex', 'str',
           'byte','bytearray','set','frozenset',            
           'tuple', 'list', 'dict','range', 'type(None)'
           'slice','Ellipsis']
        self.type_class = ['type']#内置类型和类的类型
        self.type_types = [
            'types.AsyncGeneratorType', 'types.BuiltinFunctionType',
            'types.BuiltinMethodType',
            'types.CodeType', 'types.CoroutineType',
            'types.ClassMethodDescriptorType',
            'types.FunctionType',
            'types.LambdaType','types.FrameType',
            'types.GetSetDescriptorType', 'types.GeneratorType',
            'types.MappingProxyType', 'types.MemberDescriptorType',
            'types.MethodType','types.ModuleType',
            'types.MethodWrapperType',
            'types.TracebackType', 'types.WrapperDescriptorType'
             ]
        # 'MethodDescriptorType', 'ClassMethodDescriptorType',
        #  'ModuleType' is not defined

        self.type_all = self.type_base + self.type_class + self.type_types

    def __Format_print(self,i,v,v1):
        str1=str(i).ljust(2)+'  ['+str(v).ljust(18)+']'
        str2='['+ str(v1).ljust(25)+ ']'
        str3=str(eval('type(' + 'f.' + v + ')')).ljust(30)
        print(str1,str2,str3)

    def __type_lookup(self,class_items_lst,types_lst,mode=0):
        for i, v in enumerate(class_items_lst):
            tmp = 0
            for i1, v1 in enumerate(types_lst):
                b1 = eval('isinstance(f.' + v + ',' + v1 + ')')
                if b1:
                    self.__Format_print(i, v, v1)
                    tmp += 1
                if mode=='all':
                    if (tmp == 0) and (i1 == (len(types_lst) - 1)):
                        print('NoType...?[i={};item={}]'.fromat((i,class_items_lst[i])))

    def Attribute_Method_Function_all(self, f,mode='all'):
        """ 
        查看对象的所有属性方法函数 2018/8/20 tcy shanghai yexie
            本函数运行在windows平台python3.7版本
            f 为对象,如类,类实例,函数"""

        class_items_lst = dir(f)
        types_lst = self.type_all
        self.__type_lookup(class_items_lst, types_lst)


    def Attribute(self, f):
        """ 
        查看对象的所有属性函数 2018/8/20 tcy shanghai yexie
            本函数运行在windows平台python3.7版本
            f 为对象,如类实例,函数"""

        class_items_lst = dir(f)
        types_lst = self.type_base
        self.__type_lookup(class_items_lst, types_lst)

    def Method_Function(self, f):
        """ 
        查看对象方法函数 2018/8/20 tcy shanghai yexie
            本函数运行在windows平台python3.7版本
            f 为对象,如类实例,函数"""
        # import types
        class_items_lst = dir(f)
        types_lst = self.type_types
        self.__type_lookup(class_items_lst, types_lst)


    def Builtin_Type(self, f):
        """ 
        查看对象内置方法函数 2018/8/20 tcy shanghai yexie
            本函数运行在windows平台python3.7版本
            f 为对象,如类,实例,函数"""
        # import types
        class_items_lst = dir(f)
        types_lst = self.type_types
        self.__type_lookup(class_items_lst, types_lst)

    def Sub_Class(self, f):
        print('sub class==>', f.__class__.mro())

# -----------------------------------------------------------------------------
f = AA(1111, "John")
v = view_types()
v.Attribute_Method_Function_all(f)
print('---------------------------------------------------------------------')
v.Attribute(f)
print('---------------------------------------------------------------------')
v.Method_Function(f)
print('---------------------------------------------------------------------')
v.Builtin_Type(f)
print('---------------------------------------------------------------------')
v.Sub_Class(f)

****************************************************************************************************

结果显示:

C:\python37\python.exe C:/python37/Lib/test2.py
0   [__class__         ] [type                     ]                 
1   [__delattr__       ] [types.MethodWrapperType  ]       
2   [__dict__          ] [dict                     ]                 
3   [__dir__           ] [types.BuiltinFunctionType] 
3   [__dir__           ] [types.BuiltinMethodType  ] 
4   [__doc__           ] [str                      ]                  
5   [__eq__            ] [types.MethodWrapperType  ]       
6   [__format__        ] [types.BuiltinFunctionType] 
6   [__format__        ] [types.BuiltinMethodType  ] 
7   [__ge__            ] [types.MethodWrapperType  ]       
8   [__getattribute__  ] [types.MethodWrapperType  ]       
9   [__gt__            ] [types.MethodWrapperType  ]       
10  [__hash__          ] [types.MethodWrapperType  ]       
11  [__init__          ] [types.MethodType         ]               
12  [__init_subclass__ ] [types.BuiltinFunctionType] 
12  [__init_subclass__ ] [types.BuiltinMethodType  ] 
13  [__le__            ] [types.MethodWrapperType  ]       
14  [__lt__            ] [types.MethodWrapperType  ]       
15  [__module__        ] [str                      ]                  
16  [__ne__            ] [types.MethodWrapperType  ]       
17  [__new__           ] [types.BuiltinFunctionType] 
17  [__new__           ] [types.BuiltinMethodType  ] 
18  [__reduce__        ] [types.BuiltinFunctionType] 
18  [__reduce__        ] [types.BuiltinMethodType  ] 
19  [__reduce_ex__     ] [types.BuiltinFunctionType] 
19  [__reduce_ex__     ] [types.BuiltinMethodType  ] 
20  [__repr__          ] [types.MethodWrapperType  ]       
21  [__setattr__       ] [types.MethodWrapperType  ]       
22  [__sizeof__        ] [types.BuiltinFunctionType] 
22  [__sizeof__        ] [types.BuiltinMethodType  ] 
23  [__str__           ] [types.MethodWrapperType  ]       
24  [__subclasshook__  ] [types.BuiltinFunctionType] 
24  [__subclasshook__  ] [types.BuiltinMethodType  ] 
25  [__weakref__       ] [type(None)               ]             
26  [a_id              ] [int                      ]                  
27  [a_name            ] [str                      ]                  
28  [a_show_cls        ] [types.MethodType         ]               
29  [a_show_static     ] [types.FunctionType       ]             
29  [a_show_static     ] [types.LambdaType         ]             
30  [a_x               ] [int                      ]                  
31  [cls_show          ] [types.MethodType         ]               
32  [getx              ] [types.MethodType         ]               
33  [id1               ] [int                      ]                  
34  [name1             ] [str                      ]                  
35  [setx              ] [types.MethodType         ]               
36  [show              ] [types.MethodType         ]               
37  [static_show       ] [types.FunctionType       ]             
37  [static_show       ] [types.LambdaType         ]             
38  [x                 ] [int                      ]                  
---------------------------------------------------------------------
2   [__dict__          ] [dict                     ]                 
4   [__doc__           ] [str                      ]                  
15  [__module__        ] [str                      ]                  
25  [__weakref__       ] [type(None)               ]             
26  [a_id              ] [int                      ]                  
27  [a_name            ] [str                      ]                  
30  [a_x               ] [int                      ]                  
33  [id1               ] [int                      ]                  
34  [name1             ] [str                      ]                  
38  [x                 ] [int                      ]                  
---------------------------------------------------------------------
1   [__delattr__       ] [types.MethodWrapperType  ]       
3   [__dir__           ] [types.BuiltinFunctionType] 
3   [__dir__           ] [types.BuiltinMethodType  ] 
5   [__eq__            ] [types.MethodWrapperType  ]       
6   [__format__        ] [types.BuiltinFunctionType] 
6   [__format__        ] [types.BuiltinMethodType  ] 
7   [__ge__            ] [types.MethodWrapperType  ]       
8   [__getattribute__  ] [types.MethodWrapperType  ]       
9   [__gt__            ] [types.MethodWrapperType  ]       
10  [__hash__          ] [types.MethodWrapperType  ]       
11  [__init__          ] [types.MethodType         ]               
12  [__init_subclass__ ] [types.BuiltinFunctionType] 
12  [__init_subclass__ ] [types.BuiltinMethodType  ] 
13  [__le__            ] [types.MethodWrapperType  ]       
14  [__lt__            ] [types.MethodWrapperType  ]       
16  [__ne__            ] [types.MethodWrapperType  ]       
17  [__new__           ] [types.BuiltinFunctionType] 
17  [__new__           ] [types.BuiltinMethodType  ] 
18  [__reduce__        ] [types.BuiltinFunctionType] 
18  [__reduce__        ] [types.BuiltinMethodType  ] 
19  [__reduce_ex__     ] [types.BuiltinFunctionType] 
19  [__reduce_ex__     ] [types.BuiltinMethodType  ] 
20  [__repr__          ] [types.MethodWrapperType  ]       
21  [__setattr__       ] [types.MethodWrapperType  ]       
22  [__sizeof__        ] [types.BuiltinFunctionType] 
22  [__sizeof__        ] [types.BuiltinMethodType  ] 
23  [__str__           ] [types.MethodWrapperType  ]       
24  [__subclasshook__  ] [types.BuiltinFunctionType] 
24  [__subclasshook__  ] [types.BuiltinMethodType  ] 
28  [a_show_cls        ] [types.MethodType         ]               
29  [a_show_static     ] [types.FunctionType       ]             
29  [a_show_static     ] [types.LambdaType         ]             
31  [cls_show          ] [types.MethodType         ]               
32  [getx              ] [types.MethodType         ]               
35  [setx              ] [types.MethodType         ]               
36  [show              ] [types.MethodType         ]               
37  [static_show       ] [types.FunctionType       ]             
37  [static_show       ] [types.LambdaType         ]             
---------------------------------------------------------------------
1   [__delattr__       ] [types.MethodWrapperType  ]       
3   [__dir__           ] [types.BuiltinFunctionType] 
3   [__dir__           ] [types.BuiltinMethodType  ] 
5   [__eq__            ] [types.MethodWrapperType  ]       
6   [__format__        ] [types.BuiltinFunctionType] 
6   [__format__        ] [types.BuiltinMethodType  ] 
7   [__ge__            ] [types.MethodWrapperType  ]       
8   [__getattribute__  ] [types.MethodWrapperType  ]       
9   [__gt__            ] [types.MethodWrapperType  ]       
10  [__hash__          ] [types.MethodWrapperType  ]       
11  [__init__          ] [types.MethodType         ]               
12  [__init_subclass__ ] [types.BuiltinFunctionType] 
12  [__init_subclass__ ] [types.BuiltinMethodType  ] 
13  [__le__            ] [types.MethodWrapperType  ]       
14  [__lt__            ] [types.MethodWrapperType  ]       
16  [__ne__            ] [types.MethodWrapperType  ]       
17  [__new__           ] [types.BuiltinFunctionType] 
17  [__new__           ] [types.BuiltinMethodType  ] 
18  [__reduce__        ] [types.BuiltinFunctionType] 
18  [__reduce__        ] [types.BuiltinMethodType  ] 
19  [__reduce_ex__     ] [types.BuiltinFunctionType] 
19  [__reduce_ex__     ] [types.BuiltinMethodType  ] 
20  [__repr__          ] [types.MethodWrapperType  ]       
21  [__setattr__       ] [types.MethodWrapperType  ]       
22  [__sizeof__        ] [types.BuiltinFunctionType] 
22  [__sizeof__        ] [types.BuiltinMethodType  ] 
23  [__str__           ] [types.MethodWrapperType  ]       
24  [__subclasshook__  ] [types.BuiltinFunctionType] 
24  [__subclasshook__  ] [types.BuiltinMethodType  ] 
28  [a_show_cls        ] [types.MethodType         ]               
29  [a_show_static     ] [types.FunctionType       ]             
29  [a_show_static     ] [types.LambdaType         ]             
31  [cls_show          ] [types.MethodType         ]               
32  [getx              ] [types.MethodType         ]               
35  [setx              ] [types.MethodType         ]               
36  [show              ] [types.MethodType         ]               
37  [static_show       ] [types.FunctionType       ]             
37  [static_show       ] [types.LambdaType         ]             
---------------------------------------------------------------------
sub class==> [, , ]

Process finished with exit code 0

 

你可能感兴趣的:(python)