python learning record eight

Acquiring object information: basic types can be used to determine the type

>>> type(123)
<class 'int'>
>>> type('str')
<class 'str'>
>>> type(None)
<type(None) 'NoneType'>
>>> import types
>>> def fn():
...     pass
...
>>> type(fn)==types.FunctionType
True
>>> type(abs)==types.BuiltinFunctionType
True
>>> type(lambda x: x)==types.LambdaType
True
>>> type((x for x in range(10)))==types.GeneratorType
True
Can type () determines the type of base can also be used the isinstance () is determined:

>>> isinstance('a', str)
True
>>> isinstance(123, int)
True
>>> isinstance(b'a', bytes)
True


And it may also determine whether a variable of a certain type, such as the following code can determine whether the list or tuple:

 
 
>>> isinstance([1, 2, 3], (list, tuple))
True >>> isinstance((1, 2, 3), (list, tuple)) True 
 
 

If all properties and methods of an object to be obtained, it may be used dir(), which returns a string containing the list, such as access to all properties and methods of an object str:

 
 
>>> dir('ABC')
['__add__', '__class__',..., '__subclasshook__', 'capitalize', 'casefold',..., 'zfill'] 
 
 

Similar __xxx__properties and methods in Python are all special purpose, such as __len__the method returns length. In Python, if you call the len()function attempts to get the length of an object, in fact, in len()an internal function, which automatically go to call the object's __len__()method, therefore, it is equivalent to the following code:

 
 
>>> len('ABC')
3
>>> 'ABC'.__len__() 3 


 

Guess you like

Origin www.cnblogs.com/Galesaur-wcy/p/12586513.html