On the hasattr function of getattr function in Python

Source: Internet
Author: User
Hasattr (object, name)

Action: Determines whether the object contains an attribute named name (Hasattr is implemented by calling GetAttr (Ojbect, name) to throw an exception.

Example:

>>> hasattr (list, ' append ') True >>> hasattr (list, ' Add ') False

GetAttr (Object,name,default):

function: Returns the property value of the property whose name is named Name, if the property name exists, returns its property value directly, or if the property name does not exist, The attribeterror exception is triggered or the default value is returned when the optional parameter is the default definition.

The main function of this method is to implement the reflection mechanism. This means that the method instance can be obtained through a string. In this way, you can put a method that a class might want to invoke in the configuration file and load it dynamically when needed.

Let's use a small example to illustrate their usage:

Import Func_file    #自定义python模块cs =input (' Please enter the URL to access: ') if cs== ' Loggin ': Func_file.loggin () if cs = = ' Home ': func_ File.home () If cs = = ": pass# following omitted

When I define a custom module, to invoke the method, when using if to judge, if the module in many ways, will greatly affect the efficiency of development, code redundancy is poor, obviously this is undesirable. Below we use the hasattr () function to achieve our requirements:

Examples are as follows:

Import Func_file    #自定义python模块, need to exist def run (): while True:  cs=input (' Please enter the URL to access: ')  # Hasattr takes the form of a string to manipulate (find) a member in an object (module)  if Hasattr (func_file,cs):      #判断用户输入的URL是否在func_file模块中    func=getattr ( FUNC_FILE,CS)    #有则将func_file模块下的cs函数赋值       func ()              #等同于执行func_file模块下的cs函数  Else:    print (' 404 ') #定义错误页面run ()

After we import a custom module, GATATTR can dynamically load according to the input content and use the hasattr () function to determine whether the user input is present or not, and the custom method is called if it does not exist.

is not the feeling and we open URL URL very similar Ah!

The previous example has a problem, in fact, our function function may be stored in many modules, each need to be imported separately, then we can use the GetAttr () function to load the module dynamically? Of course you can!

Take a look at the example:

def run (): while True:  cs=input (' Please enter: ')  v,k=cs.split ('/') #获得输入的模块和模块的方法  obj=__import__ (' lib. ') +v,fromlist=true) #调用lib目录下的模块fromlist =true import  if Hasattr (obj,k) by Path connection:    f= getattr (obj,k)    f ()  else:    print (' 404 ') if __name__ = = ' __main__ ':   run ()

is not feel getattr very strong ah. In fact, GetAttr () is a block that realizes Python's reflection, and in combination with other methods such as SetAttr (), dir (), we can also make a lot of interesting things.

This article on the GetAttr function in Python hasattr function is the small part of the whole content to share to everyone, hope to give you a reference, but also hope that we support the script home.

  • 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.