How to get object information in Python _python

Source: Internet
Author: User

When we get a reference to an object, how do we know what kind of object it is and what are the methods?
use Type ()

First, we'll determine the object type, using the type () function:

Basic types can be judged by type ():

>>> 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 determine:

>>> type (ABS)
<type ' Builtin_function_or_method ' >
>>> Type (a)
<class ' __ main__. Animal ' >

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

>>> type (123) ==type (456)
true
>>> type (' abc ') ==type (' 123 ')
true
>> > Type (' abc ') ==type (123)
False

But this kind of writing is too troublesome, Python has defined constants for each type, placed in the types module, before using, you need to import:

>>> Import Types
>>> type (' abc ') ==types. StringType
True
>>> type (U ' abc ') ==types. Unicodetype
True
>>> type ([]) ==types. ListType
True
>>> type (str) ==types. Typetype
True

Finally, it is noted that there is a type called typetype, and that the type of all types is typetype, such as:

>>> type (int) ==type (str) ==types. Typetype
True

Using Isinstance ()

It is inconvenient to use type () for the inheritance relationship of class. To determine the type of class, you can use the Isinstance () function.

We review the last example if the inheritance relationship is:

Copy Code code as follows:
Object-> Animal-> Dog-> Husky

So, isinstance () can tell us if an object is of some kind. Create 3 types of objects First:

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

Then, Judge:

>>> isinstance (H, Husky)
True

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

To judge again:

>>> isinstance (H, Dog)
True

H is a type of husky, but since husky is inherited from dog, H is also dog. In other words, isinstance () determines whether an object is the type itself, or is located on the parent inheritance chain of that type.

So, we can be sure that H is still the animal type:

>>> isinstance (H, Animal)
True

Similarly, the actual type is dog D is also the animal type:

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

However, D is not a husky type:

Basic types that can be judged by type () can also be judged by isinstance ():

>>> isinstance (' a ', str)
true
>>> isinstance (U ' a ', Unicode)
true
>>> Isinstance (' A ', Unicode)
False

You can also determine whether a variable is one of several 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 both STR and Unicode are inherited from Basestring, the above code can also be simplified to:

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

Using Dir ()

If you want to get all the properties and methods of an object, you can use the Dir () function, which returns a list containing the strings, 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 ', ' Splitli Nes ', ' startswith ', ' strip ', ' swapcase ', ' title ', ' Translate ', ' upper ', ' Zfill '] 

Properties and methods like __xxx__ are used in Python for special purposes, such as the __len__ method returns the length. In Python, if you call the Len () function to try to get the length of an object, in fact, within the Len () function, it automatically invokes the object's __len__ () method, so the following code is equivalent:

>>> len (' abc ')
3
>>> ' abc '. __LEN__ ()
3

We write our own class, if we also want to use Len (myobj), we write a __len__ () method:

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

The rest are normal properties or methods, such as lower (), which returns a lowercase string:

>>> ' abc '. LOWER ()
' abc '

Simply listing the attributes and methods is not enough, with GetAttr (), SetAttr (), and hasattr (), we can manipulate the state of an object directly:

>>> 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 ') # has attribute ' x '?
True
>>> obj.x
9
>>> hasattr (obj, ' y ') # has attribute ' y '?
False
>>> setattr (obj, ' y ', 19) # set an attribute ' y '
>>> hasattr (obj, ' y ') # has attribute ' y '?
True
>>> getattr (obj, ' y ') # get attribute ' y '
>>> obj.y # Get property ' y '
19

If you attempt to obtain a property that does not exist, a attributeerror error is thrown:

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

>>> getattr (obj, ' z ', 404) # Get property ' Z ', if not present, return default value 404
404

You can also obtain the object's methods:

>>> hasattr (obj, ' power ') # has attribute ' power '?
True
>>> getattr (obj, ' power ') # Gets the property ' power '
<bound method Myobject.power of <__main__. MyObject object at 0x108ca35d0>>
>>> fn = getattr (obj, ' power ') # get attribute ' power ' and assign value to variable fn
>> > fn # fn points to Obj.power
<bound method Myobject.power of <__main__. MyObject object at 0x108ca35d0>>
>>> fn () # calling FN () is the same as calling Obj.power ()
81

Summary

With a built-in series of functions, we can dissect any Python object and get the data inside. It should be noted that only when we do not know the object information, we will go to get 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 need to determine whether the FP object exists a read method, and if so, it is a stream and cannot be read if it does not exist. Hasattr () came in handy.

Note that in a dynamic language like Python, the Read () method does not mean that the FP object is a file stream, it may also 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 function of reading the image.

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.