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'
#定义类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!