Home >Backend Development >Python Tutorial >Detailed introduction to Python's built-in getattr function
English documentation:
getattr(object, name[, default])
AttributeError is raised.
#定义类Student >>> class Student: def __init__(self,name): self.name = name >>> s = Stduent('Aim') >>> getattr(s,'name') #等效于调用s.name 'Aim' >>> s.name 'Aim'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'
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!