python的types模塊


python的types模塊

1.types是什么:

  • types模塊中包含python中各種常見的數據類型,如IntType(整型),FloatType(浮點型)等等。
>>> 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__']


2.types常見用法:

# 100是整型嗎?
>>> isinstance(100, types.IntType)
True

>>>type(100)
int

# 看下types的源碼就會發現types.IntType就是int
>>> types.IntType is int
True

  • 但有些類型並不是int這樣簡單的數據類型:

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'>

  • python中總有些奇奇怪怪的類型。有些類型默認python中沒有像int那樣直接就有,單但其實也可以自己定義的。
>>> 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

  • 瞬間感覺types模塊號low,直接用type都能代替。。事實就是這樣

3.MethodType動態的給對象添加實例方法:

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()

  • 如果不用MethodType而是直接a.bark = bark的話,需要在調用bark時額外傳遞self參數,這不是我們想要的。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM