Python 面向对象-获取对象信息 type isinstance getattr setattr hasattr


一、type()函数

判断基本数据类型可以直接写intstr等:

>>> class Animal(object):
...    pass
...
>>> type(123)
<class 'int'>
>>> type('123')
<class 'str'>
>>> type(None)
<class 'NoneType'>
>>> type(abs)
<class 'builtin_function_or_method'>
>>> type(Animal())
<class '__main__.Animal'>

 

 >>> type(123) == type(456)
True
>>> type(123) == int
True

判断一个对象是否是函数:

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

二、isinstance()函数

对于class的继承关系来说,使用type()就很不方便。如果要判断class的类型,可以使用isinstance()函数。

>>> class Animal(object):
...    pass
...
>>> class Dog(Animal):
...    pass
...
>>> d = Dog()
>>> isinstance(d, Dog)
True
>>> isinstance(d, Animal)
True

用isinstance()判断基本类型:

1 >>> isinstance('a', str)
2 True
3 >>> isinstance(123, int)
4 True
5 >>> isinstance(b'a', bytes)
6 True

并且还可以判断一个变量是否是某些类型中的一种,比如下面的代码就可以判断是否是list或者tuple:

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

优先使用isinstance()判断类型,可以将指定类型及其子类“一网打尽”。

三、dir()函数

如果要获得一个对象的所有属性和方法,可以使用dir()函数,它返回一个包含字符串的list,比如,获得一个str对象的所有属性和方法:

>>> dir('abc')
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__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']

列表中类似__xxx__的属性和方法在Python中都是有特殊用途的,比如__len__方法返回长度。在Python中,如果你调用len()函数试图获取一个对象的长度,实际上,在len()函数内部,它自动去调用该对象的__len__()方法,所以,下面的代码是等价的:

1 >>> len('abc')
2 3
3 >>> 'abc'.__len__()
4 3

自己写的类,如果也想用len(myObj)的话,就自己写一个__len__()方法:

>>> class MyDog(object):
...    def __len__(self):
...        return 100
...
>>> dog = MyDog()
>>> len(dog)
100

列表中剩下的都是普通属性或方法,比如lower()返回小写的字符串:

1 >>> 'abc'.upper()
2 'ABC'

四、getattr()setattr()以及hasattr()

测试该对象的属性:

>>> class MyObject(object):
...    def __init__(self):
...        self.x = 9
...    def power(self):
...        return self.x * self.x
...
>>> obj = MyObject()
>>> hasattr(obj, 'x')
True
>>> hasattr(obj, 'y')
False
>>>
>>> setattr(obj, 'y', 20)
>>> hasattr(obj, 'y')
True
>>> getattr(obj, 'y')
20
>>> getattr(obj, 'z')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'MyObject' object has no attribute 'z'
>>> getattr(obj, 'z', 100)    # 指定默认值
100

测试该对象的方法:

>>> hasattr(obj, 'power')
True
>>> getattr(obj, 'power')
<bound method MyObject.power of <__main__.MyObject object at 0x1014be400>>
>>> fn = getattr(obj, 'power')
>>> fn
<bound method MyObject.power of <__main__.MyObject object at 0x1014be400>>
>>> fn()
81

相关内容