How to Use getattr() Function in PythonPython Basics


The getattr() function is a built-in function that is used to get the value of an object’s named property.

Example

#!/usr/bin/python
# -*- coding: UTF-8 -*-

class temp(object):
    A = 1

a = temp()
print(getattr(a, 'A') )   # Get the attribute bar

Output:

1

Syntax

getattr(object, name[, default])

Parameters

Name Description
object Object whose named attribute’s value is to be returned.
name The string which contains the attribute’s name.
default The value which is to be returned when the named attribute is not found.

Return Value

It returns the value of the named attribute of the given object.

© 2024 Cheerlearn.com, all rights reserved. Privacy Policy | Contact Us