在我们之前的教程中,我们了解了 python系统命令在本教程中,我们将讨论Python getattr()函数。
Python getattr() 函数
Python **getattr() 函数用于获取对象属性的值,如果没有发现该对象的属性,则返回默认值. 基本上,返回默认值是您可能需要使用 Python getattr() 函数的主要原因。
1getattr(object_name, attribute_name[, default_value])
Python getattr() 示例
在本节中,我们将学习如何使用getattr()
函数访问对象的属性值,假设我们正在写一个名为学生
的类,学生类的基本属性是student_id
和student_name
。
1class Student:
2 student_id=""
3 student_name=""
4
5 # initial constructor to set the values
6 def __init__(self):
7 self.student_id = "101"
8 self.student_name = "Adam Lam"
9
10student = Student()
11# get attribute values by using getattr() function
12print('\ngetattr : name of the student is =', getattr(student, "student_name"))
13
14# but you could access this like this
15print('traditional: name of the student is =', student.student_name)
So, the output will be like this
Python getattr() 默认值
在本节中,我们将使用 python getattr() 默认值选项. 如果您想要访问不属于对象的任何属性,那么您可以使用 getattr() 默认值选项. 例如,如果 student_cgpa
属性对学生不存在,则会显示默认值。
1class Student:
2 student_id=""
3 student_name=""
4
5 # initial constructor to set the values
6 def __init__(self):
7 self.student_id = "101"
8 self.student_name = "Adam Lam"
9
10student = Student()
11# using default value option
12print('Using default value : Cgpa of the student is =', getattr(student, "student_cgpa", 3.00))
13# without using default value
14try:
15 print('Without default value : Cgpa of the student is =', getattr(student, "student_cgpa"))
16except AttributeError:
17 print("Attribute is not found :(")
所以,运行代码后,你会得到这样的输出
1Using default value : Cgpa of the student is = 3.0
2Attribute is not found :(
请注意,当在调用 getattr() 函数时未提供默认值时,将AttributeError
调用。
使用 Python getattr() 函数的原因
使用python getattr() 的主要原因是,我们可以通过使用属性名称作为 String 来获得该值,所以您可以从控制台手动输入属性名称,如果属性未找到,您可以设置一些默认值,这使我们能够完成一些不完整的数据。如果您的学生类正在进行工作,那么我们可以使用 getattr() 函数来完成其他代码。一旦学生类有这个属性,它会自动接收它,而不是使用默认值。