Python getattr()
时间:2020-02-23 14:42:45 来源:igfitidea点击:
在之前的教程中,我们了解了python系统命令。
在本教程中,我们将讨论Python getattr()函数。
Python getattr()函数
Python getattr()函数用于获取对象属性的值,如果找不到该对象的属性,则返回默认值。
基本上,返回默认值是您可能需要使用Python getattr()函数的主要原因。
因此,在开始本教程之前,让我们看一下Python的getattr()函数的基本语法。
getattr(object_name, attribute_name[, default_value])
Python getattr()示例
在本节中,我们将学习如何使用getattr()函数访问对象的属性值。
假设我们正在编写一个名为Student
的类。
学生类的基本属性是student_id
和student_name
。
现在,我们将创建一个Student类的对象并访问它的属性。
class Student: student_id="" student_name="" # initial constructor to set the values def __init__(self): self.student_id = "101" self.student_name = "Adam Lam" student = Student() # get attribute values by using getattr() function print('\ngetattr : name of the student is =', getattr(student, "student_name")) # but you could access this like this print('traditional: name of the student is =', student.student_name)
因此,输出将如下所示
Python getattr()默认值
在本节中,我们将使用python getattr()默认值选项。
如果要访问不属于该对象的任何属性,则可以使用getattr()默认值选项。
例如,如果学生不存在" student_cgpa"属性,则将显示默认值。
在下面的示例中,我们将看到默认值的示例。
我们还将学习如果属性不存在并且我们没有使用默认值选项时会发生什么。
class Student: student_id="" student_name="" # initial constructor to set the values def __init__(self): self.student_id = "101" self.student_name = "Adam Lam" student = Student() # using default value option print('Using default value : Cgpa of the student is =', getattr(student, "student_cgpa", 3.00)) # without using default value try: print('Without default value : Cgpa of the student is =', getattr(student, "student_cgpa")) except AttributeError: print("Attribute is not found :(")
因此,运行代码后,您将获得如下输出
Using default value : Cgpa of the student is = 3.0 Attribute is not found :(
注意,当调用getattr()函数时未提供默认值时,会引发" AttributeError"。
使用Python getattr()函数的原因
使用python getattr()的主要原因是我们可以通过使用属性名称作为String来获取值。
因此,您可以从控制台在程序中手动输入属性名称。
同样,如果找不到属性,则可以设置一些默认值,这使我们能够完成一些不完整的数据。
同样,如果您的Student类正在进行中,那么我们可以使用getattr()函数来完成其他代码。
学生类拥有此属性后,它将自动选择它,并且不使用默认值。