Python getattr() Built in Function

Python getattr() is a built-in function that returns the value of a named attribute of an object. It can also take a default value as an optional argument, which is returned if the attribute does not exist.

Here are some examples of how to use Python getattr():

To get the value of an existing attribute of an object:

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


person = Person()
print(getattr(person, "name"))
# returns "John"
print(getattr(person, "age")) # returns 36

To get the value of a non-existing attribute of an object with a default value:

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


person = Person()
print(getattr(person, "city", "Unknown"))
# returns "Unknown"

To implement a custom getattr() method for an object that dynamically computes attribute values:

class Square:
    def __init__(self, side):
        self.side = side


    def __getattr__(self, attr):
        if attr == "area":
            return self.side ** 2
        elif attr == "perimeter":
            return self.side * 4

        else:
            raise AttributeError(f"{self.__class__.__name__} has no attribute {attr}")


square = Square(5)
print(getattr(square, "area"))
# returns 25
print(getattr(square, "perimeter")) # returns 20
print(getattr(square, "color")) # raises AttributeError

If you have any questions about this code, you can drop a line in comment.

 

Comments

Popular posts from this blog

Python chr() Built in Function

Python The _ Operator

Python bool() Built in Function

Python Printing Readable Results

Python One Liner Functions