
python 获取对象信息
判断对象是什么类型 使用type()
基本类型都可以用type()判断
1 | type(123) #<class int> |
如果一个变量指向函数或者类,也可以使用type()判断1
2type(abs) #<class 'builtin_function_or_method'>
type(a) #<class '__main__.Animal'>
可以使用if判断两个类型是否相等
判断基本类型1
2a = 'str'
type(a) == str #输出 True
判断一个对象是否是一个函数?1
2
3
4
5
6
7import 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的类型,可以使用isinstance()函数
object -> Animal -> Dog -> Husky (继承关系)
1 | a = Animal() |
判断1
2isinstance(h,Husky) #True
isinstance(h, Animal) #True 因为h是从Animal继承下来的
能用type()判断的基本类型也可以用isinstance()
获得一个对象的所有属性和方法
dir()
要获得一个对象的所有属性和方法,它返回一个包含字符串的list
eg:要获得str对象的所有属性和方法1
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']
仅仅把属性和方法列出来是不够的,配合getattr()、setattr()以及hasattr(),我们可以直接操作一个对象的状态
1 | class MyObject(object): |
如果试图获取不存在的属性,会抛出AttributeError的错误
可以传入一个default参数,如果属性不存在,就返回默认值:
getattr(obj, ‘z’, 404)
也可以将对象的方法单独赋值给某个变量
fn = getattr(obj, ‘power’) # 获取属性’power’并赋值到变量fn
小结
通过内置的一系列函数,我们可以对任意一个Python对象进行剖析,拿到其内部的数据。要注意的是,只有在不知道对象信息的时候,我们才会去获取对象信息
(实例属性和类属性)[https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014319117128404c7dd0cf0e3c4d88acc8fe4d2c163625000]
给实例绑定属性的方法是通过实例变量,或者通过self变量1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18class Student(object):
def __init__(self, name):
self.name = name
s = Student('Bob')
s.score = 90 #理解 只有s这个实例才存在 score这个属性 Student这个类并不受影响
s.name #因为实例并没有name属性,所以会继续查找class的name属性
Student.name # 打印类的name属性
#理解
s.name = 'Michael' # 给实例绑定name属性 由于实例属性优先级比类属性高,因此,它会屏蔽掉类的name属性
Student.name # 但是类属性并未消失,用Student.name仍然可以访问
del s.name # 如果删除实例的name属性
s.name # 再次调用s.name,由于实例的name属性没有找到,类的name属性就显示出来了