获取对象的类型:
>>> type(123)
<class 'int'>
>>> type('str')
<class 'str'>
>>> type(None)
<class 'NoneType'>
>>>
复制代码
以上是通过type()这个函数来获取123,str,None的对象类型
判断两个类型是否相同:
>>> type(123)==type(456)
True
>>> type('str')== str
True
>>> type('abc')== type('def')
True
>>> type(123) == int
True
>>> type(123) == type('abc')
False
复制代码
判断一个对象是不是函数:
>>> import types
>>> def fn():
... pass
...
>>> type(fn)==types.FunctionType
True
>>> type(abs)==types.BuiltinFunctionType
True
>>> type(abs)==types.FunctionType
False
>>> type(lambda x : x)==types.LambdaType
True
>>> type((x for x in range(10)))==types.GeneratorType
True
复制代码
使用isinstance() 进行判断类型:
>>> class Animal(object):
... def run():
... print('running...')
...
>>> class Dog(Animal):
... def run():
... pass
...
>>> a = Animal()
>>> d = Dog()
>>> isinstance(d, Dog)
True
复制代码
我们看看子类的对象和父类的关系:
>>> isinstance(d, Dog) and isinstance(d, Animal)
True
复制代码
前面我们说过,子类的对象也是属于父类类型,所以上面返回是true
type 判断类型跟isinstance是一样的:
>>> isinstance('a', str)
True
>>> isinstance(123, int)
True
>>> isinstance(b'c', bytes)
True
>>>
复制代码
使用dir()获取一个对象的所有方法和属性:
>>> dir('abc')
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__',
'__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__',
'__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__',
'__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__',
'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs',
'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit',
'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper',
'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex',
'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip',
'swapcase', 'title', 'translate', 'upper', 'zfill']
>>>
复制代码
总结:
1、通过type()判断对象类型
2、还可以通过isinstance() 判断对象类型
3、通过dir()获取对象的方法和属性
复制代码
ps:程序员要注意健康,健康知识: 鼻子不通气很难受,可以看看这个链接:https://zhidao.baidu.com/question/135383907.html 我正在尝试揉搓和洗鼻方式,看看效果~。