Python built-in getattr function details

Source: Internet
Author: User
This article describes the detailed description of the Python built-in getattr function in English:

  • Getattr (object, name [, default])

  • Return the value of the named attribute of object. name must be a string. if the string is the name of one of the object's attributes, the result is the value of that attribute. for example, getattr (x, 'foobar') is equivalent to x. foobar. if the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.


Note:

  • 1. the function is to obtain the attribute named name from the object, which is equivalent to calling object. name.

# Define class Student >>> class Student: def _ init _ (self, name): self. name = name >>> s = Stduent ('aim ') >>> getattr (s, 'name') # It is equivalent to calling s. name 'aim '> s. name 'aim'

2. the default parameter of the third function is an optional parameter. if the object contains the name attribute, the value of the name attribute is returned. if the name attribute is not present, the default value is returned. if the default parameter is not input, an error is returned.

# Define class Student >>> class Student: def _ init _ (self, name): self. name = name >>> getattr (s, 'name') # property name'aim '>>> getattr (s, 'age', 6) # property age does not exist, however, the default value is provided. the default value >>> getattr (s, 'age') is returned. # The Property age does not exist. if the default value is not provided, Traceback (most recent call last) is returned. File"
 
  
", Line 1, in
  
   
Getattr (s, 'age') AttributeError: 'stduent' object has no attribute 'age'
  
 

The above is a detailed description of the Python built-in getattr function. For more information, see other related articles in the first PHP community!

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.