Python 中的 getattr() 函数有什么作用?
Python getattr()
getattr() 方法返回一个对象的指定属性的值。如果未找到,则返回提供给该函数的默认值。
语法
getattr() 方法的语法如下 −
getattr(object, name[, default])
getattr() 方法可以采用多个参数 −
getattr() 方法返回 −
给定对象的指定属性的值
默认值,如果未找到指定属性
AttributeError 异常,如果未找到指定属性且未定义默认值
示例
class Male:
age = 21
name = "Abel"
x = Male()
print('The age is:', getattr(x, "age"))
print('The age is:', x.age)输出
这将给出输出
('The age is:', 21)
('The age is:', 21)
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP