1. type()
type() 函数如果你只有第一个参数则返回对象的类型,三个参数返回新的类型对象。
type() 不会认为子类是一种父类类型,不考虑继承关系。
type() 方法的语法:
type(object)
type(name, bases, dict)
参数:
- name -- 类的名称。
- bases -- 基类的元组。
- dict -- 字典,类内定义的命名空间变量。
返回值:
一个参数返回对象类型, 三个参数,返回新的类型对象。
基本类型都可以用type()
判断:
>>> type(123)
<class 'int'>
>>> type('123')
<class 'str'>
>>> type(None)
<class 'NoneType'>
如果一个变量指向函数或者类,也可以用type()
判断:
>>> def add1(a,b):
... return a+b
...
>>>
>>> type(add1)
<class 'function'>
>>>
>>> type(abs)
<class 'builtin_function_or_method'>
>>>
>>>
>>> class Animal:
... def run(self):
... print('animal is running ...')
...
>>>
>>> animal = Animal()
>>>
>>> type(animal)
<class '__main__.Animal'>
>>>
>>> class Dog(Animal):
... pass
...
>>>
>>> dog = Dog()
>>>
>>> type(dog)
<class '__main__.Dog'>
type()
函数返回对应的Class类型。如果我们要在 if
语句中判断,就需要比较两个变量的 type 类型是否相同:
>>> type(123) == type(456)
True
>>>
>>> type(123) == int
True
>>>
>>> type('zth') == str
True
>>>
>>> type('zth') == type(123)
False
>>>
可以使用 types
模块中定义的常量判断一个对象是否是函数:
>>> 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
2. isinstance()
isinstance() 函数来判断一个对象是否是一个已知的类型,类似 type()。
isinstance() 与 type() 区别:
type() 不会认为子类是一种父类类型,不考虑继承关系。
isinstance() 会认为子类是一种父类类型,考虑继承关系。
如果要判断两个类型是否相同推荐使用 isinstance()。
isinstance() 方法的语法:
isinstance(object, classinfo)
参数:
- object -- 实例对象。
- classinfo -- 可以是直接或间接类名、基本类型或者由它们组成的元组。
返回值:
如果对象的类型与参数二的类型(classinfo)相同则返回 True,否则返回 False。。
>>> isinstance( 123 , int)
True
>>>
>>> isinstance( '123' , int)
False
>>>
>>> isinstance( '123' , str)
True
>>>
>>>
>>> isinstance( [1,2,3] , list)
True
>>>
>>> isinstance( '123' , (int,str,list)) # 是元组中的一个返回 True
True
对于class的继承关系来说,使用type()
就很不方便。我们要判断class的类型,可以使用isinstance()
函数。
>>> class Animal:
... def run(self):
... print('animal is running ...')
...
>>>
>>> animal = Animal()
>>>
>>> class Dog(Animal):
... pass
...
>>>
>>> dog = Dog()
>>>
>>> isinstance(dog,Dog)
True
>>> isinstance(dog,Animal)
True
>>> isinstance(dog,object)
True
>>>
>>> isinstance(animal,Animal)
True
>>>
>>> isinstance(animal,Dog)
False
>>>
>>> isinstance(dog,Animal) and isinstance(dog,Dog)
True
3. dir()
如果要获得一个对象的所有属性和方法,可以使用dir()
函数,它返回一个包含字符串的list,比如,获得一个str对象的所有属性和方法:
>>> 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', 'isascii', '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']