Home > Backend Development > Python Tutorial > Detailed introduction to Python's built-in getattr function

Detailed introduction to Python's built-in getattr function

高洛峰
Release: 2017-03-21 11:10:21
Original
1350 people have browsed it

English documentation:

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


Description:

  •  1. The function is to obtain the attribute named name from the object object, which is 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'
Copy after login
2. The third parameter default of the function is an optional parameter. If the name attribute in the object means, the value of the name attribute is returned. If there is no name attribute, the default value is returned. If default value is not passed in, an error will be reported.

#定义类Student
>>> class Student:
    def __init__(self,name):
        self.name = name
>>> getattr(s,'name') #存在属性name
'Aim'
>>> getattr(s,'age',6) #不存在属性age,但提供了默认值,返回默认值
>>> getattr(s,'age') #不存在属性age,未提供默认值,调用报错
Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    getattr(s,'age')
AttributeError: 'Stduent' object has no attribute 'age'
Copy after login

The above is the detailed content of Detailed introduction to Python's built-in getattr function. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template