Python built-in functions (25) -- getattr, pythongetattr

Source: Internet
Author: User

Python built-in functions (25) -- getattr, pythongetattr

English document:

getattr( Object, Name[, Default])
Return the value of the named attribute Object. NameMust 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 x.foobar. If the named attribute does not exist, DefaultIs returned if provided, otherwise AttributeErrorIs 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 6> 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 "<pyshell #17>", line 1, in <module> getattr (s, 'age') AttributeError: 'stduent' object has no attribute 'age'

 

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.