Python hasattr() Built in Function

Python hasattr() is a built-in function that returns True if an object has a given attribute, otherwise False. An attribute can be a variable, a method, a property, etc. that belongs to an object.

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

To check if an object has an attribute defined in its class:

class Car:
    brand = "Ford"
    number = 7786


car = Car()
print(hasattr(car, "brand"))
# returns True
print(hasattr(car, "color")) # returns False

To check if an object has an attribute defined dynamically:

class Person:
    name = "John"
    age = 36


person = Person()
person.country = "Norway"
# defines a new attribute dynamically
print(hasattr(person, "country")) # returns True

To check if an object has a method or a property:

class Circle:
    def __init__(self, radius):
        self.radius = radius


    def area(self): # defines a method
        return 3.14 * self.radius ** 2


    @property
    def diameter(self):
# defines a property
        return 2 * self.radius


circle = Circle(5)
print(hasattr(circle, "area")) # returns True
print(hasattr(circle, "diameter")) # returns True

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

Stock Market Predictions with LSTM in Python

Collections In Python

Python Count Occurrence Of Elements

Python One Liner Functions