>>> import types >>> dir(types) ['BooleanType', 'BufferType', 'BuiltinFunctionType', 'BuiltinMethodType', 'ClassType', 'CodeType', 'ComplexType', 'DictProxyType', 'DictType', 'DictionaryType', 'EllipsisType', 'FileType', 'FloatType', 'FrameType', 'FunctionType', 'GeneratorType', 'GetSetDescriptorType', 'InstanceType', 'IntType', 'LambdaType', 'ListType', 'LongType', 'MemberDescriptorType', 'MethodType', 'ModuleType', 'NoneType', 'NotImplementedType', 'ObjectType', 'SliceType', 'StringType', 'StringTypes', 'TracebackType', 'TupleType', 'TypeType', 'UnboundMethodType', 'UnicodeType', 'XRangeType', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__']
# 100是整型吗? >>> isinstance(100, types.IntType) True >>>type(100) int # 看下types的源码就会发现types.IntType就是int >>> types.IntType is int True
class Foo: def run(self): return None def bark(self): print('barking') a = Foo() print(type(1)) print(type(Foo)) print(type(Foo.run)) print(type(Foo().run)) print(type(bark))
输出结果:
<class 'int'> <class 'type'> <class 'function'> <class 'method'> <class 'function'>
>>> import types >>> class Foo: def run(self): return None def bark(self): print('barking') # Foo.run是函数吗? >>> isinstance(Foo.run, types.FunctionType) True # Foo().run是方法吗? >>> isinstance(Foo().run, types.MethodType) True # 其实: >>> types.FunctionType is type(Foo.run) True >>> types.MethodType is type(Foo().run) True
import types class Foo: def run(self): return None def bark(self): print('i am barking') a = Foo() a.bark = types.MethodType(bark, a) a.bark()
原文链接:https://www.cnblogs.com/PrettyTom/p/6664808.html