Rumah  >  Artikel  >  pembangunan bahagian belakang  >  Python面向对象之获取对象信息

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

不言
不言asal
2018-04-14 10:28:111594semak imbas

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

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

使用type()

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

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

>>> type(123)
<class &#39;int&#39;>
>>> type(&#39;jeff&#39;)
<class &#39;str&#39;>
>>> type(True)
<class &#39;bool&#39;>
>>> type(None)
<class &#39;NoneType&#39;>

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

>>> type(abs)
<class &#39;builtin_function_or_method&#39;>

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

>>> type(123) == type(456)
True
>>> type(&#39;jeff&#39;) == type(&#39;1993&#39;)
True
>>> type(&#39;jeff&#39;) == str
True
>>> type(123) == int
True
>>> type(123) == type(&#39;jeff&#39;)
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(&#39;Animal is running...&#39;)

class Dog(Animal):
    def run(self):
        print(&#39;Dog is haha running...&#39;)

    def eat(self):
        print(&#39;Eating meat...&#39;)
class Cat(Animal):
    def run(self):
        print(&#39;Cat is miaomiao running...&#39;)

    def eat(self):
        print(&#39;Eating fish...&#39;)
class Husky(Dog):
    def run(self):
        print(&#39;Husky is miaomiao running...&#39;)
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(&#39;a&#39;,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)
[&#39;__abs__&#39;, &#39;__add__&#39;, &#39;__and__&#39;, &#39;__bool__&#39;, &#39;__ceil__&#39;, &#39;__class__&#39;, &#39;__delattr__&#39;, &#39;__dir__&#39;, &#39;__pmod__&#39;, &#39;__doc__&#39;, &#39;__eq__&#39;, &#39;__float__&#39;, &#39;__floor__&#39;, &#39;__floorp__&#39;, &#39;__format__&#39;, &#39;__ge__&#39;, &#39;__getattribute__&#39;, &#39;__getnewargs__&#39;, &#39;__gt__&#39;, &#39;__hash__&#39;, &#39;__index__&#39;, &#39;__init__&#39;, &#39;__int__&#39;, &#39;__invert__&#39;, &#39;__le__&#39;, &#39;__lshift__&#39;, &#39;__lt__&#39;, &#39;__mod__&#39;, &#39;__mul__&#39;, &#39;__ne__&#39;, &#39;__neg__&#39;, &#39;__new__&#39;, &#39;__or__&#39;, &#39;__pos__&#39;, &#39;__pow__&#39;, &#39;__radd__&#39;, &#39;__rand__&#39;, &#39;__rpmod__&#39;, &#39;__reduce__&#39;, &#39;__reduce_ex__&#39;, &#39;__repr__&#39;, &#39;__rfloorp__&#39;, &#39;__rlshift__&#39;, &#39;__rmod__&#39;, &#39;__rmul__&#39;, &#39;__ror__&#39;, &#39;__round__&#39;, &#39;__rpow__&#39;, &#39;__rrshift__&#39;, &#39;__rshift__&#39;, &#39;__rsub__&#39;, &#39;__rtruep__&#39;, &#39;__rxor__&#39;, &#39;__setattr__&#39;, &#39;__sizeof__&#39;, &#39;__str__&#39;, &#39;__sub__&#39;, &#39;__subclasshook__&#39;, &#39;__truep__&#39;, &#39;__trunc__&#39;, &#39;__xor__&#39;, &#39;bit_length&#39;, &#39;conjugate&#39;, &#39;denominator&#39;, &#39;from_bytes&#39;, &#39;imag&#39;, &#39;numerator&#39;, &#39;real&#39;, &#39;to_bytes&#39;]
>>> dir(&#39;jeff&#39;)
[&#39;__add__&#39;, &#39;__class__&#39;, &#39;__contains__&#39;, &#39;__delattr__&#39;, &#39;__dir__&#39;, &#39;__doc__&#39;, &#39;__eq__&#39;, &#39;__format__&#39;, &#39;__ge__&#39;, &#39;__getattribute__&#39;, &#39;__getitem__&#39;, &#39;__getnewargs__&#39;, &#39;__gt__&#39;, &#39;__hash__&#39;, &#39;__init__&#39;, &#39;__iter__&#39;, &#39;__le__&#39;, &#39;__len__&#39;, &#39;__lt__&#39;, &#39;__mod__&#39;, &#39;__mul__&#39;, &#39;__ne__&#39;, &#39;__new__&#39;, &#39;__reduce__&#39;, &#39;__reduce_ex__&#39;, &#39;__repr__&#39;, &#39;__rmod__&#39;, &#39;__rmul__&#39;, &#39;__setattr__&#39;, &#39;__sizeof__&#39;, &#39;__str__&#39;, &#39;__subclasshook__&#39;, &#39;capitalize&#39;, &#39;casefold&#39;, &#39;center&#39;, &#39;count&#39;, &#39;encode&#39;, &#39;endswith&#39;, &#39;expandtabs&#39;, &#39;find&#39;, &#39;format&#39;, &#39;format_map&#39;, &#39;index&#39;, &#39;isalnum&#39;, &#39;isalpha&#39;, &#39;isdecimal&#39;, &#39;isdigit&#39;, &#39;isidentifier&#39;, &#39;islower&#39;, &#39;isnumeric&#39;, &#39;isprintable&#39;, &#39;isspace&#39;, &#39;istitle&#39;, &#39;isupper&#39;, &#39;join&#39;, &#39;ljust&#39;, &#39;lower&#39;, &#39;lstrip&#39;, &#39;maketrans&#39;, &#39;partition&#39;, &#39;replace&#39;, &#39;rfind&#39;, &#39;rindex&#39;, &#39;rjust&#39;, &#39;rpartition&#39;, &#39;rsplit&#39;, &#39;rstrip&#39;, &#39;split&#39;, &#39;splitlines&#39;, &#39;startswith&#39;, &#39;strip&#39;, &#39;swapcase&#39;, &#39;title&#39;, &#39;translate&#39;, &#39;upper&#39;, &#39;zfill&#39;]
>>> dir(&#39;abc&#39;)  File "<stdin>", line 1
    dir(&#39;abc&#39;)
       ^
SyntaxError: invalid character in identifier注意括号要英文下的括号

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

>>> len(&#39;asd&#39;)
3
>>> &#39;asd&#39;.__len__()
3

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

>>> &#39;ASDD&#39;.lower()
&#39;asdd&#39;

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

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

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

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

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

>>> getattr(obj,&#39;Z&#39;,404)
404

也可以获得对象的方法:

>>> hasattr(obj, &#39;power&#39;) # 有属性&#39;power&#39;吗?
True
>>> getattr(obj, &#39;power&#39;) # 获取属性&#39;power&#39;
<bound method MyObject.power of <__main__.MyObject object at
0x10077a6a0>>
>>> fn = getattr(obj, &#39;power&#39;) # 获取属性&#39;power&#39;并赋值到变量 fn
>>> fn # fn 指向 obj.power
<bound method MyObject.power of <__main__.MyObject object at
0x10077a6a0>>
>>> fn() # 调用 fn()与调用 obj.power()是一样的
81

相关推荐:

Python面向对象之继承和多态

Python面向对象之访问限制

Python面向对象之类和实例














Atas ialah kandungan terperinci Python面向对象之获取对象信息. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn