Home > Article > Backend Development > Introduction to Python functions: Introduction and examples of hasattr function
Introduction to Python functions: Introduction and examples of hasattr function
In Python, hasattr() is a built-in function. Its main function is to check whether an object has a specified property or method and return a Boolean value to indicate whether it exists. The use of this function is very simple, only need to provide two parameters: an object and a string. Returns True if this object has the same properties or methods as the string, False otherwise. Let's introduce the usage of this function in detail.
Function syntax
hasattr(obj, name)
Parameter description
obj: Specify the object to be checked.
name: Specifies the name of the attribute or method to be checked, which is a string.
Return value
If the object has the specified property or method, it returns True, otherwise it returns False.
Example
The following uses a specific example to demonstrate how to use the hasattr() function.
# 创建一个新的类 class Person: name = "张三" age = 25 def say_hello(self): print("你好,我是", self.name) # 创建一个实例对象 p = Person() # 检查实例是否有指定的属性或方法 result1 = hasattr(p, 'name') # 检查是否有name属性 result2 = hasattr(p, 'age') # 检查是否有age属性 result3 = hasattr(p, 'gender') # 检查是否有gender属性 result4 = hasattr(p, 'say_hello') # 检查是否有say_hello方法 result5 = hasattr(p, 'run') # 检查是否有run方法 # 打印检查结果 print(result1) # 输出 True print(result2) # 输出 True print(result3) # 输出 False print(result4) # 输出 True print(result5) # 输出 False
In this example, we define a class named Person, which has two attributes: name and age, and a method named say_hello. Then we create an instance object p and use the hasattr() function to check whether it has the specified attribute or method. The results are as follows:
In actual development, we can use this function to determine whether an object has certain properties or methods, thereby determining whether to execute some specific code blocks.
The above is the detailed content of Introduction to Python functions: Introduction and examples of hasattr function. For more information, please follow other related articles on the PHP Chinese website!