English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriel de base en Python

Contrôle de flux en Python

Fonctions en Python

Types de données en Python

Opérations sur les fichiers en Python

Objets et classes en Python

Dates et heures en Python

Connaissances avancées en Python

Manuel de référence Python

Méthode d'utilisation de getattr() en Python et exemples

Python built-in functions

The getattr() method returns the value of the named attribute of the object. If not found, it will return the default value provided to the function.

The syntax of the getattr() method is:

getattr(object, name[, default])

The above syntax is equivalent to:

object.name

getattr() parameters

The getattr() method takes multiple parameters:

  • object -The object to return the named attribute value of

  • name -A string containing the name of the attribute

  • default (optional) -The value returned when the named attribute is not found

getattr() return value

The getattr() method returns:

  • The value of the named attribute of the given object

  • default if the named attribute is not found

  • AttributeError exception if the named attribute is not found and no default value is defined

Example1How does getattr() work in Python?

class Person:
    age = 23
    name = "Adam"
person = Person()
print('Age is:', getattr(person, "age"))
print('Age is:', person.age)

When running the program, the output is:

Age is: 23
Age is: 23

Example2getattr() when the named attribute is not found

class Person:
    age = 23
    name = "Adam"
person = Person()
# When a default value is provided
print('Gender is:', getattr(person, 'sex', 'Male'))
# When no default value is provided
print('Gender is:', getattr(person, 'sex'))

When running the program, the output is:

Gender is: Male
AttributeError: 'Person' object has no attribute 'sex'

The named attribute 'sex' does not exist in the Person class. Therefore, when the getattr() method is called with the default value 'Male', it will return 'Male'.

However, if we do not provide any default values, an AttributeError statement will be raised when the named attribute 'sex' is not found, that is, the object does not have a 'sex' attribute.

Python built-in functions