Detailed description of the functions of the getattr and hasattr functions in Python

Source: Internet
Author: User
This article mainly introduces the functions of getattr and hasattr functions in Python. it is of great reference value. For more information, see hasattr (object, name)

Purpose: Determine whether the object contains the feature named name (hasattr is implemented by calling getattr (ojbect, name) to check whether an exception is thrown ).

Example:

>>> hasattr(list, 'append')True >>> hasattr(list, 'add')False getattr(object,name,default):

Purpose: return the property value of the property named name of the object. if the property name exists, the property value is directly returned. if the property name does not exist, the AttribetError exception is triggered or the default value is returned when the optional parameter default is defined.

The main function of this method is to implement the reflection mechanism. That is to say, you can use strings to obtain the method instance. In this way, you can place the methods that a class may call in the configuration file and dynamically load them as needed.

Below we use small examples to illustrate their usage:

Import func_file # Custom python module cs = input ('Enter the URL to access: ') if cs = 'loggin': func_file.loggin () if cs = 'home ': func_file.home () if cs = '': pass # The following is omitted:

When I define a custom module to call the methods in it and use if to judge, if many methods are used in the module, the development efficiency and code redundancy are greatly affected, obviously, this is not desirable. The following describes how to use the hasattr () function to meet our needs:

Example:

Import func_file # Custom python module. def run (): while True: cs = input must exist in advance ('Enter the URL to access :') # hasattr uses strings to perform operations (search) on the object (module) member if hasattr (func_file, cs ): # determine whether the URL entered by the user is in the func_file module func = getattr (func_file, cs) # If yes, assign the cs function under the func_file module to func () # equivalent to executing the cs function else: print ('000000') in the func_file Module # defining the error page run ()

After importing a custom module, gatattr can dynamically load the input content and use the hasattr () function to determine whether the input exists. if the input does not exist, the custom method is called.

Is it similar to opening a URL!

In the previous example, there is a problem. in actual situations, our function may be stored in many modules, and each function needs to be imported separately. can we use getattr () how does a function dynamically load a module? Of course.

See the example:

Def run (): while True: cs = input ('Enter: ') v, k = cs. split ('/') # obtain the input module and module method obj =__ import _ ('Lib. '+ v, fromlist = True) # Call the module fromlist = True in the lib directory to import if hasattr (obj, k) by path connection: f = getattr (obj, k) f () else: print ('000000') if _ name _ = '_ main _': run ()

Does getattr sound powerful. In fact, getattr () is a building block for implementing python reflection. we can also do a lot of interesting things by combining other methods such as setattr () and dir.

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.