Tutorials  /  Python

Python getattr() Function Tutorial

Ccentron Redaktion · February 2024 ·3 min read ·Python, Tutorial

In this tutorial we will be discussing about Python getattr() function.

VM

Try it yourself: cloud servers from €3.12/month

ccloud³ VMs from German data centers – deployed in seconds, billed by the hour, with a €200 starting credit for new accounts. Launch a server →

Python getattr() Function

Python getattr() function is used to get the value of an object’s attribute and if no attribute of that object is found, default value is returned. Basically, returning the default value is the main reason why you may need to use Python getattr() function. So, before starting the tutorial, let's see the basic syntax of Python’s getattr() function.

Code
getattr(object_name, attribute_name[, default_value])

Python getattr() Example

In this section, we will learn how to access attribute values of an object using getattr() function. Suppose, we are writing a class named Student. The basic attributes of Student class are student_id and student_name. Now we will create an object of the class Student and access its attribute.

Python
class Student:
    student_id=""
    student_name=""

    def __init__(self):
        self.student_id = "101"
        self.student_name = "Adam Lam"

student = Student()
print('\ngetattr : name of the student is =', getattr(student, "student_name"))
print('traditional: name of the student is =', student.student_name)

So, the output will be like this:

Code
getattr : name of the student is = Adam Lam
traditional: name of the student is = Adam Lam

Python getattr() Default Value

In this section, we will use the python getattr() default value option. If you want to access any attribute that doesn’t belong to the object, then you can use the getattr() default value option. For example, if the student_cgpa attribute is not present for the student, then will show a default value. In the following example, we will see example of default value. We will also learn what happens if the attribute is not present and we are not using the default value option.

Python
class Student:
    student_id=""
    student_name=""

    def __init__(self):
        self.student_id = "101"
        self.student_name = "Adam Lam"

student = Student()
print('Using default value : Cgpa of the student is =', getattr(student, "student_cgpa", 3.00))
try:
    print('Without default value : Cgpa of the student is =', getattr(student, "student_cgpa"))
except AttributeError:
    print("Attribute is not found :(")

So, after running the code you will get output like this:

Code
Using default value : Cgpa of the student is = 3.0
Attribute is not found :(

Notice that AttributeError is raised when the default value is not provided while calling getattr() function.

Reason for Using Python getattr() Function

The main reason to use python getattr() is that we can get the value by using the name of the attribute as String. So you can manually input the attribute name in your program from console. Again, if an attribute is not found you can set some default value, which enables us to complete some of our incomplete data. Also if your Student class is work in progress, then we can use getattr() function to complete other code. Once Student class has this attribute, it will automatically pick it up and not use the default value. So, that’s all about python getattr() function.

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie Python
Teilen
Noch offene Fragen?

Our team will help you with your specific setup - in German or English, by people who run the platform themselves.

War dieses Tutorial hilfreich?

Your answer is stored anonymously and helps us improve our tutorials.

Kommentare

No comments yet - be the first to ask a question about this tutorial.

Sign in to comment

Comments are open to centron customers. Sign in to your account to ask a question about this tutorial.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren