Python gets object information

Source: Internet
Author: User

When we get a reference to an object, how do we know what kind of object it is and what methods it has?

Use Type ()

First, let's judge the object type and use the type() function:

Basic types can be type() judged by:

>>> type(123)<type ‘int‘>>>> type(‘str‘)<type ‘str‘>>>> type(None)<type ‘NoneType‘>

If a variable points to a function or class, it can also be type() judged by:

>>> type(abs)<type ‘builtin_function_or_method‘>>>> type(a)<class ‘__main__.Animal‘>

But type() what type does the function return? It returns the type types. If we want to if judge in a statement, we need to compare the type of the two variables:

>>> type(123)==type(456)True>>> type(‘abc‘)==type(‘123‘)True>>> type(‘abc‘)==type(123)False

But this is too cumbersome, Python defines each type as a constant, put it in a types module, and it needs to be imported before it can be used:

>>> import types>>> type(‘abc‘)==types.StringTypeTrue>>> type(u‘abc‘)==types.UnicodeTypeTrue>>> type([])==types.ListTypeTrue>>> type(str)==types.TypeTypeTrue

Finally, notice that there is a type called TypeType , and the type of all types itself is TypeType , for example:

>>> type(int)==type(str)==types.TypeTypeTrue
Using Isinstance ()

The use of type () is inconvenient for class inheritance relationships. We want to determine the class type, and we can use the isinstance() function.

We review the last example, if the inheritance relationship is:

object -> Animal -> Dog -> Husky

Then, isinstance() you can tell us whether an object is of a certain type. Create 3 types of objects First:

>>> a = Animal()>>> d = Dog()>>> h = Husky()

Then, Judge:

>>> isinstance(h, Husky)True

No problem, because h the variable is pointing to the Husky object.

To judge again:

>>> isinstance(h, Dog)True

hAlthough it is a husky type, it is also the dog type since husky is inherited from the dog h . In other words, isinstance() you determine whether an object is the type itself, or is on the parent inheritance chain of that type.

So we can be sure, h or the animal type:

>>> isinstance(h, Animal)True

In the same vein, the actual type is dog and the d animal type:

>>> isinstance(d, Dog) and isinstance(d, Animal)True

However, it d is not a husky type:

>>> isinstance(d, Husky)False

type()the basic type of judgment can also be isinstance() judged by:

>>> isinstance(‘a‘, str)True>>> isinstance(u‘a‘, unicode)True>>> isinstance(‘a‘, unicode)False

You can also determine whether a variable is one of some types, such as the following code to determine whether it is STR or Unicode:

>>> isinstance(‘a‘, (str, unicode))True>>> isinstance(u‘a‘, (str, unicode))True

Since str and unicode are inherited from basestring , so you can also simplify the above code to:

>>> isinstance(u‘a‘, basestring)True
Use Dir ()

If you want to get all the properties and methods of an object, you can use a dir() function that returns a list that contains a string, for example, to get all the properties and methods of a str object:

  >>> dir (' ABC ') [' __add__ ', ' __class__ ', ' __contains__ ', ' __delattr__ ', ' __doc__ ', ' __eq__ ', ' __ Format__ ', ' __ge__ ', ' __getattribute__ ', ' __getitem__ ', ' __getnewargs__ ', ' __getslice__ ', ' __gt__ ', ' __hash__ ', ' __ Init__ ', ' __le__ ', ' __len__ ', ' __lt__ ', ' __mod__ ', ' __mul__ ', ' __ne__ ', ' __new__ ', ' __reduce__ ', ' __reduce_ex__ ', ' __ Repr__ ', ' __rmod__ ', ' __rmul__ ', ' __setattr__ ', ' __sizeof__ ', ' __str__ ', ' __subclasshook__ ', ' _formatter_field_name_ Split ', ' _formatter_parser ', ' capitalize ', ' center ', ' count ', ' decode ', ' encode ', ' endswith ', ' expandtabs ', ' Find ', ' Format ', ' Index ', ' isalnum ', ' isalpha ', ' isdigit ', ' islower ', ' isspace ', ' istitle ', ' isupper ', ' join ', ' ljust ', ' lower ', ' Lstrip ', ' partition ', ' replace ', ' rfind ', ' rindex ', ' rjust ', ' rpartition ', ' rsplit ', ' Rstrip ', ' Split ', ' Splitlines ', ' st Artswith ', ' strip ', ' swapcase ', ' title ', ' Translate ', ' upper ', ' Zfill ']  

Similar __xxx__ properties and methods are used in Python for special purposes, such as the __len__ method returns the length. In Python, if you call len() a function to try to get the length of an object, in fact, len() inside the function, it automatically calls the method of the object, __len__() so the following code is equivalent:

>>> len(‘ABC‘)3>>> ‘ABC‘.__len__()3

We write our own class, if you want to use it len(myObj) , we write a __len__() method:

>>> class MyObject(object):...     def __len__(self):...         return 100...>>> obj = MyObject()>>> len(obj)100

All that is left is a normal property or method, such as lower() a string that returns lowercase:

>>> ‘ABC‘.lower()‘abc‘

Simply listing properties and methods is not enough, mates getattr() , setattr() and hasattr() , we can directly manipulate the state of an object:

>>> class MyObject(object):...     def __init__(self):...         self.x = 9...     def power(self):...         return self.x * self.x...>>> obj = MyObject()

Immediately thereafter, you can test the properties of the object:

>>> hasattr(obj, ‘x‘) # 有属性‘x‘吗?True>>> obj.x9>>> hasattr(obj, ‘y‘) # 有属性‘y‘吗?False>>> setattr(obj, ‘y‘, 19) # 设置一个属性‘y‘>>> hasattr(obj, ‘y‘) # 有属性‘y‘吗?True>>> getattr(obj, ‘y‘) # 获取属性‘y‘19>>> obj.y # 获取属性‘y‘19

If you try to get a property that does not exist, you throw a attributeerror error:

>>> getattr(obj, ‘z‘) # 获取属性‘z‘Traceback (most recent call last):  File "<stdin>", line 1, in <module>AttributeError: ‘MyObject‘ object has no attribute ‘z‘

You can pass in a default parameter and, if the property does not exist, return the defaults:

>>> getattr(obj, ‘z‘, 404) # 获取属性‘z‘,如果不存在,返回默认值404404

You can also get the method of the object:

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

With the built-in series of functions, we can parse any Python object and get its internal data. It is important to note that we only get object information when we do not know the object information. If you can write directly:

sum = obj.x + obj.y

Don't write it:

sum = getattr(obj, ‘x‘) + getattr(obj, ‘y‘)

An example of the correct usage is as follows:

def readImage(fp):    if hasattr(fp, ‘read‘):        return readData(fp)    return None

Assuming that we want to read the image from the file stream FP, we first determine whether the FP object has a read method, and if so, it is a stream and cannot be read if it does not exist. hasattr()comes in handy.

Note that in a dynamic language such as Python, there is a read() method that does not mean that the FP object is a file stream, it may be a network stream, or it may be a byte stream in memory, but as long as the read() method returns valid image data, it does not affect the ability to read the image.

Python gets object information

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.