Python built-in function (--GETATTR)

Source: Internet
Author: User

English documents:

getattr ( object, name[, default])
Return the value of the named attribute of object. name must is a string. The If the string is the name of the one of the object ' s attributes, and the result is the value of this attribute. For example, was getattr(x, ‘foobar‘) equivalent to x.foobar . If the named attribute does not exist, the default is returned if provided, and otherwise is AttributeError raised.
Gets the property value of the object
Description
  
1. The function function is to get the property named name from Object objects, equivalent to calling Object.name.
#定义类Student >>> class Student:    def __init__ (self,name):        self.name = name        >>> s = stduent ( ' Aim ') >>> getattr (S, ' name ') #等效于调用s. Name ' aim ' >>> s.name ' aim '

2. Function The third parameter of the default is an optional parameter, if the object in the meaning of the Name property, the value of the Name property is returned, if there is no Name property, the default value is returned, if default does not pass in the value, then an error.

#定义类Student >>> class Student:    def __init__ (self,name):        self.name = name>>> getattr (s, ' name ') #存在属性name ' Aim ' >>> getattr (S, ' age ', 6) #不存在属性age, but provided a default value that returns the default value 6>>> getattr (S, ' age ') #不存在属性age, Default value not provided, call error Traceback (most recent called last):  File "<pyshell#17>", line 1, in <module>    getattr (S, ' Age ') Attributeerror: ' Stduent ' object with no attribute ' age '

Python built-in function (--GETATTR)

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.