您好,欢迎访问一九零五行业门户网

Python面向对象之获取对象信息

本篇文章给大家分享的内容是关于python面向对象之获取对象信息,有着一定的参考价值,有需要的朋友可以参考一下
当我们拿到一个对象的引用时,如何知道这个对象是什么类型、有哪些方法呢?
使用type()首先,我们来判断对象类型,使用type()函数:
基本类型都可以使用type()判断:
>>> type(123) <class 'int'> >>> type('jeff') <class 'str'> >>> type(true) <class 'bool'> >>> type(none) <class 'nonetype'>
如果一个变量指向函数或者类,也可以用type()判断:
>>> type(abs) <class 'builtin_function_or_method'>
但是type()函数返回的是什么类型呢?它返回对应的class类型。如果我们要在if语句中判断,就需要比较两个变量的type类型是否相同:
>>> type(123) == type(456) true >>> type('jeff') == type('1993') true >>> type('jeff') == str true >>> type(123) == int true >>> type(123) == type('jeff') false
判断基本数据类型可以直接写int、str等,但如果要判断一个对象是否是函数怎么办?可以使用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
使用 isinstance()
对于class的继承关系来说,使用type()就很不方便。我们要判断class的类型,就可以使用isinstance()函数。
我们回顾上次的例子如果继承关系是:
object、animal、dog、husky
class animal(object): def run(self): print('animal is running...') class dog(animal): def run(self): print('dog is haha running...') def eat(self): print('eating meat...') class cat(animal): def run(self): print('cat is miaomiao running...') def eat(self): print('eating fish...') class husky(dog): def run(self): print('husky is miaomiao running...') dog = dog() dog.run() dog.eat() xinxin = husky() xinxin.run() cat = cat() cat.run() cat.eat()
dog is haha running... eating meat... husky is miaomiao running... cat is miaomiao running... eating fish...
那么,isinstance()就可以告诉我们,一个对象是否是某种类型。先创建3中类型的对象:
a= animal() d = dog() h = husky() print(isinstance(h,husky)) print(isinstance(h,dog)) print(isinstance(h,animal)) print(isinstance(h,object)) print(isinstance('a',str)) print(isinstance(123,int))
true true true true true true
print(isinstance(d,husky)) false
并且还可以判断一个变量是否是某些类型中的一种,比如下面的代码就可以判断是否是list或者tuple:
>>> isinstance([1,2,3],(tuple,list)) true >>> isinstance((1,2,3),(tuple,list)) true >>> isinstance(1,(tuple,list)) false
使用dir()如果要获得一个对象的所有属性和方法,可以使用dir()函数,它返回一个包含字符串的list,比如,获得一个str对象的所有属性和方法:
>>> dir(123) ['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__pmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floorp__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rpmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloorp__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruep__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truep__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes'] >>> dir('jeff') ['__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']
>>> dir('abc') file "<stdin>", line 1 dir('abc') ^ syntaxerror: invalid character in identifier注意括号要英文下的括号
类似__xxx__的属性和方法再python中都是有特殊用途的,比如__len__方法返回长度。在python中,如果你调用len()函数试图获取一个对象的长度,实际上,在len()函数内部,它自动去调用该对象的__len__()方法,所以,下面的代码是等价的:
>>> len('asd') 3 >>> 'asd'.__len__() 3
剩下的都是普通属性或方法,比如lower()返回小写的字符串:
>>> 'asdd'.lower() 'asdd'
仅仅把属性和方法列出来是不够的,配合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 >>> obj.x 9 >>> hasattr(obj,'y') false >>> setattr(obj,'y',19) >>> hasattr(obj,'y') true >>> getattr(obj,'y') 19
如果试图获取不存在的属性,会抛出attributeerror的错误:
>>> getattr(obj,'z') traceback (most recent call last): file "<stdin>", line 1, in <module> attributeerror: 'myobject' object has no attribute 'z' >>>
可以传入一个default参数,如果属性不存在,就反回默认值:
>>> getattr(obj,'z',404) 404
也可以获得对象的方法:
>>> hasattr(obj, 'power') # 有属性'power'吗? true >>> getattr(obj, 'power') # 获取属性'power' <bound method myobject.power of <__main__.myobject object at 0x10077a6a0>> >>> fn = getattr(obj, 'power') # 获取属性'power'并赋值到变量 fn >>> fn # fn 指向 obj.power <bound method myobject.power of <__main__.myobject object at 0x10077a6a0>> >>> fn() # 调用 fn()与调用 obj.power()是一样的 81
相关推荐:
python面向对象之继承和多态
python面向对象之访问限制
python面向对象之类和实例
以上就是python面向对象之获取对象信息的详细内容。
其它类似信息

推荐信息