How to use the hasattr function of the builtins library in Python

How to use the hasattr function of the builtins library in Python


In Python, hasattr functions are part of the builtins module and are used to check whether an object has a given property. Its basic syntax is as follows:

hasattr(object, name)

here:

  • object: This is the object whose properties are to be checked.
  • name: This is the name of the property to check.

hasattrThe function returns a Boolean value, True if the object has the given property, False otherwise.

For example:

class MyClass:  
    def __init__(self):  
        self.my_attribute = 123  
  
my_obj = MyClass()  
print(hasattr(my_obj, 'my_attribute'))  # 输出:True  
print(hasattr(my_obj, 'another_attribute'))  # 输出:False

In this example, MyClassan instance of my_objhas a my_attributeproperty named, so hasattr(my_obj, 'my_attribute')True is returned. However, my_objthere is no another_attributeproperty named, so hasattr(my_obj, 'another_attribute')False is returned.

General catalog of "AUTOSAR lineage decomposition (ETAS tool chain)"

Guess you like

Origin blog.csdn.net/PlutoZuo/article/details/132849021
Recommended