Introduction to the getattr function hasattr function and getattrhasattr function in python

Source: Internet
Author: User

Introduction to the getattr function hasattr function and getattrhasattr function in python

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:Returns 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.

The above discussion about the getattr function hasattr function in python is all the content that I have shared with you. I hope you can give me a reference and support the help house.

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.