/  Getattr() method in Python Built in Function

Getattr() method in Python Built in Function

getattr method in built in function returns frozenset object which an immutable. It is initialized with the elements from the given Iterable.

 

Syntax:

getattr(object, name[, default])

 

Parameters

getattr method has 3 parameters.

  1. Object:this is the part whose named attribute’s value has to be returned.
  2. Name:in this parameter there is a string which contains the attributes name.
  3. Default:when the named attribute is not found, default value is returned.

 

Example-1:

 

When attribute is found in getattr method

class Person:
  name = "Jennie"
  age = 36
  country = "Norway"
x = getattr(Person, 'name')
print(x)

 

Output:

Getattr () method in Python Built in Function

 

Example-2:

 

When attribute is not found in getattr method

class Person:
    age = 23
    name = "Anna"
person = Person()
print('The gender is:', getattr(person, 'gender'))

 

Output:

Getattr () method in Python Built in Function