Python getattr() Function

Example

Get the value of the "age" attribute of the "Person" object:

class Person:
  name = "Bill"
  age = 63
  country = "USA"
x = getattr(Person, 'age')

Run Instance

Definition and Usage

The getattr() function returns the value of the specified attribute from the specified object.

Syntax

getattr(object, attribute, default)

Parameter Value

Parameter Description
object Required. Object.
attribute The name of the attribute from which you want to get the value.
default Optional. The value returned when the attribute does not exist.

More Examples

Example

If the attribute does not exist, please use the "default" parameter to write a message:

class Person:
  name = "Bill"
  age = 63
  country = "USA"
x = getattr(Person, 'page', 'my message')

Run Instance

Related Pages

Reference Manual:delattr() Function(Delete attribute)

Reference Manual:hasattr() Function(Check if the attribute exists)

Reference Manual:setattr() Function(Set attribute value)