PHP前端开发

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

百变鹏仔 2小时前 #Python
文章标签 面向对象

本篇文章给大家分享的内容是关于Python面向对象之获取对象信息,有着一定的参考价值,有需要的朋友可以参考一下

当我们拿到一个对象的引用时,如何知道这个对象是什么类型、有哪些方法呢?

使用type()

首先,我们来判断对象类型,使用type()函数:

基本类型都可以使用type()判断:

&gt;&gt;&gt; type(123)<class>&gt;&gt;&gt; type('jeff')<class>&gt;&gt;&gt; type(True)<class>&gt;&gt;&gt; type(None)<class></class></class></class></class>

如果一个变量指向函数或者类,也可以用type()判断:

&gt;&gt;&gt; type(abs)<class></class>

但是type()函数返回的是什么类型呢?它返回对应的Class类型。如果我们要在if语句中判断,就需要比较两个变量的type类型是否相同:

立即学习“Python免费学习笔记(深入)”;

&gt;&gt;&gt; type(123) == type(456)True&gt;&gt;&gt; type('jeff') == type('1993')True&gt;&gt;&gt; type('jeff') == strTrue&gt;&gt;&gt; type(123) == intTrue&gt;&gt;&gt; type(123) == type('jeff')False

判断基本数据类型可以直接写int、str等,但如果要判断一个对象是否是函数怎么办?可以使用types模块中定义的常量:

&gt;&gt;&gt; import types&gt;&gt;&gt; def fn():...     pass...&gt;&gt;&gt; type(fn) == types.FunctionTypeTrue&gt;&gt;&gt; type(abs) == types.BuiltinFunctionTypeTrue&gt;&gt;&gt; type(lambda x:x) == types.LambdaTypeTrue&gt;&gt;&gt; type((x for x in range(10))) == types.GeneratorTypeTrue

使用 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))
TrueTrueTrueTrueTrueTrue
print(isinstance(d,Husky))False

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

&gt;&gt;&gt; isinstance([1,2,3],(tuple,list))True&gt;&gt;&gt; isinstance((1,2,3),(tuple,list))True&gt;&gt;&gt; isinstance(1,(tuple,list))False

使用dir()

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

&gt;&gt;&gt; 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']&gt;&gt;&gt; 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']
&gt;&gt;&gt; dir('abc')  File "<stdin>", line 1    dir('abc')       ^SyntaxError: invalid character in identifier注意括号要英文下的括号</stdin>

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

&gt;&gt;&gt; len('asd')3&gt;&gt;&gt; 'asd'.__len__()3

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

&gt;&gt;&gt; 'ASDD'.lower()'asdd'

仅仅把属性和方法列出来是不够的,配合getattr()、setattr()以及hasattr(),我们可以直接操作一个对象的状态:

&gt;&gt;&gt; class MyObject(object):...     def __init__(self):...         self.x = 9...     def power(self):...         return self.x*self.x&gt;&gt;&gt;&gt;&gt;&gt; obj = MyObject()&gt;&gt;&gt; hasattr(obj,'x')True&gt;&gt;&gt; obj.x9&gt;&gt;&gt; hasattr(obj,'y')False&gt;&gt;&gt; setattr(obj,'y',19)&gt;&gt;&gt; hasattr(obj,'y')True&gt;&gt;&gt; getattr(obj,'y')19

如果试图获取不存在的属性,会抛出AttributeError的错误:

&gt;&gt;&gt; getattr(obj,'Z')Traceback (most recent call last):  File "<stdin>", line 1, in <module>AttributeError: 'MyObject' object has no attribute 'Z'&gt;&gt;&gt;</module></stdin>

可以传入一个default参数,如果属性不存在,就反回默认值:

&gt;&gt;&gt; getattr(obj,'Z',404)404

也可以获得对象的方法:

&gt;&gt;&gt; hasattr(obj, 'power') # 有属性'power'吗?True&gt;&gt;&gt; getattr(obj, 'power') # 获取属性'power'<bound>&gt;&gt;&gt;&gt; fn = getattr(obj, 'power') # 获取属性'power'并赋值到变量 fn&gt;&gt;&gt; fn # fn 指向 obj.power<bound>&gt;&gt;&gt;&gt; fn() # 调用 fn()与调用 obj.power()是一样的81</bound></bound>