How to obtain object information in Python, and how to obtain object information in python

Source: Internet
Author: User

How to obtain object information in Python, and how to obtain object information in python

When we get an object reference, how do we know the object type and methods?
Use type ()

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

You can use type () to determine the basic types:

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

If a variable points to a function or class, you can also use type () to judge:

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

But what type is returned by the type () function? It returns the type. If we want to judge in the if statement, we need to compare whether the types of the two variables are the same:

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

However, this writing method is too troublesome. Python defines constants for each type and puts them in the types module. before using this method, you must first import:

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

Finally, we noticed that there is a type called TypeType, and the types of all types are TypeType. For example:

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

Use isinstance ()

It is inconvenient to use type () for the class inheritance relationship. To determine the class type, use the isinstance () function.

Let's review the previous example. If the inheritance relationship is:

Copy codeThe Code is as follows: object-> Animal-> Dog-> Husky

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

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

Then, Judge:

>>> isinstance(h, Husky)True

No problem, because the h variable points to the Husky object.

Judge again:

>>> isinstance(h, Dog)True

H is of the Husky type, but since it is inherited from Dog, h is also of the Dog type. In other words, isinstance () determines whether an object is of this type or is located on the parent inheritance chain of this type.

Therefore, we can be sure that h or Animal type:

>>> isinstance(h, Animal)True

Similarly, the actual type is Dog's d and Animal type:

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

However, d is not of the Husky type:

The basic types that can be determined by type () can also be determined by isinstance:

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

You can also determine whether a variable is of certain types. For example, the following code can determine whether it is str or unicode:

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

Because both str and unicode are inherited from basestring, you can also simplify the above Code:

>>> isinstance(u'a', basestring)True

Use dir ()

To obtain all attributes and methods of an object, you can use the dir () function, which returns a list containing strings. For example, you can obtain all attributes 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', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

Attributes and methods similar to _ xxx _ have special purposes in Python, such as the return length of the _ len _ method. In Python, if you call the len () function to obtain the length of an object, in fact, inside the len () function, it automatically calls the _ len _ () method of the object. Therefore, the following code is equivalent:

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

If you want to use len (myObj), write a _ len _ () method:

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

The rest are common attributes or methods. For example, lower () returns a lowercase string:

>>> 'ABC'.lower()'abc'

It is not enough to list attributes and methods. In combination with getattr (), setattr (), and hasattr (), we can directly operate on the status of an object:

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

Then, you can test the attributes of the object:

>>> Hasattr (obj, 'x') # Is there an attribute 'X? True >>> obj. x9 >>> hasattr (obj, 'y') # Is there an attribute 'y? False >>> setattr (obj, 'y', 19) # Set an attribute 'y' >>> hasattr (obj, 'y') # Do you have an attribute 'y? True >>> getattr (obj, 'y') # Get the property 'y' 19 >>> obj. y # Get the property 'y' 19

If you try to obtain a property that does not exist, the error AttributeError will be thrown:

You can input a default parameter. If the property does not exist, the default value is returned:

>>> Getattr (obj, 'z', 404) # obtain the property 'Z'. If the property does not exist, the default value 404404 is returned.

You can also obtain the object method:

>>> Hasattr (obj, 'power') # Do you have the attribute 'power? True >>> getattr (obj, 'power') # obtain the attribute 'power' <bound method MyObject. power of <__ main __. myObject object at 0x0000ca35d0 >>> fn = getattr (obj, 'power') # obtain the attribute 'power' and assign the value to the variable fn >>> fn # fn points to obj. power <bound method MyObject. power of <__ main __. myObject object at 0x0000ca35d0 >>>> fn () # Call fn () and call obj. power () is the same 81

Summary

Through a series of built-in functions, we can analyze any Python object and obtain its internal data. Note that object information is obtained only when we do not know the object information. If you can directly write:

sum = obj.x + obj.y

Do not write:

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

An example of a correct usage is as follows:

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

If we want to read images from the file stream fp, we must first determine whether the fp object has the read method. If so, the object is a stream and cannot be read if it does not exist. Hasattr () comes in handy.

Note that in dynamic languages such as Python, the read () method does not mean that the fp object is a file stream or a network stream, it may also be a byte stream in the memory, but as long as the read () method returns valid image data, it does not affect the image reading function.

Related Article

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.