Cara menggunakan python getattr function call

❮ Built-in Functions


Example

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

class Person:
  name = "John"
  age = 36
  country = "Norway"

x = getattr(Person, 'age')

Try it Yourself »


Definition and Usage

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


Syntax

getattr(object, attribute, default)

Parameter Values

ParameterDescriptionobjectRequired. An object.attributeThe name of the attribute you want to get the value fromdefaultOptional. The value to return if the attribute does not exist

More Examples

Example

Use the "default" parameter to write a message when the attribute does not exist:

class Person:
  name = "John"
  age = 36
  country = "Norway"

x = getattr(Person, 'page', 'my message')

Try it Yourself »


The delattr() function, to remove an attribute

The hasattr() function, to check if an attribute exist

The setattr() function, to set the value of an attribute


❮ Built-in Functions


Now, we can access the attributes of the

>>> book.title
'Moby Dick'
7 instance. Nothing is more natural than using dot notation to do that.

>>> book.title
'Moby Dick'

We can do the same thing by using

>>> book.title
'Moby Dick'
5 function:

>>> getattr(book, 'title')
'Moby Dick'

So

>>> book.title
'Moby Dick'
9 and
>>> getattr(book, 'title')
'Moby Dick'
0 are exactly the same things! They are the same except for:

  • >>> getattr(book, 'title')
    'Moby Dick'
    1 attribute passes as a string (
    >>> getattr(book, 'title')
    'Moby Dick'
    2) to
    >>> book.title
    'Moby Dick'
    5 function.
  • You can pass a default value as an argument.

For example:

>>> book.language

will raise an error because the

>>> book.title
'Moby Dick'
6 class does not have such an attribute.

Traceback (most recent call last):
File "<input>", line 1, in <module>
AttributeError: 'Book' object has no attribute 'language'

Instead, we can do:

>>> getattr(book, 'language', 'English')
'English'

Keep in mind that without the default value, it also raises an error.

>>> getattr(book, 'language')

Output:

Traceback (most recent call last):
File "<input>", line 1, in <module>
AttributeError: 'Book' object has no attribute 'language'

Because

>>> book.title
'Moby Dick'
5 and dot notation are equivalent if you don’t pass the default value.

If you’re adventurous (just like me), you might be wondering whether it is also possible to access a method of a class. Let’s see:

>>> getattr(book, 'describe')

Output:

<bound method Book.describe of <__main__.Book object at 0x103cd7a0>>

It returns

>>> getattr(book, 'title')
'Moby Dick'
6 method without calling it. Remember that functions are also objects and you can assign them to the variables. So we can either call it directly by adding parentheses to the end

>>> book.title
'Moby Dick'
0

or we can store this value and call it later.

>>> book.title
'Moby Dick'
1

So far so good! You may ask: Isn’t it weird to access an attribute because we’ve already known the content of a class?

In fact,

>>> book.title
'Moby Dick'
5 comes in handy in case you need to decide which attribute will be used while the program is already running. For example, in web applications, you might need to get the attributes dynamically based on the coming request. Or you get the name of the attributes from users.

Suppose you make a program that receives inputs from users and prints the value of the desired attribute of

>>> book.title
'Moby Dick'
7 .

>>> book.title
'Moby Dick'
2

Let’s say the user writes

>>> getattr(book, 'title')
'Moby Dick'
9 as input. Then the output is:

>>> book.title
'Moby Dick'
3

The code above is equivalent to:

>>> book.title
'Moby Dick'
4

It really shortens our code, right?

Let’s look at another example. Now, you get allowed HTTP methods dynamically from an API, and you send the appropriate HTTP request via requests lib based on the allowed method (POST or PUT). Of course, you need to use

>>> book.title
'Moby Dick'
5.

which is equivalent to:

As you see,

>>> book.title
'Moby Dick'
5 makes our life easier and reduces code repetitions.

If you’re in a similar situation and your object has many attributes, using this function saves you from writing many if-elif clauses.

If you really intend to write long code lines because of not using

>>> book.title
'Moby Dick'
5 and you think you succeed by copying and pasting again and again. Well… I have bad news for you. Most of the programming errors are caused by copy-paste operations. So this function also protects you from the potential errors from copy-paste.

In summary, if you know the name of the attribute, always use dot notation. However, when the name of the attribute is given as program flows, you should use

>>> book.title
'Moby Dick'
5.