Home >Backend Development >Python Tutorial >Introduction to Python functions: usage and examples of getattr function
Python function introduction: usage and examples of getattr function
In Python, getattr() is a built-in function used to obtain the attribute value of an object. Without knowing the object's attribute name, you can use the getattr() function to dynamically access the attribute. This article will introduce the syntax, usage and examples of the getattr() function.
The syntax of the getattr() function is as follows:
getattr(object, name[, default])
Parameter description:
If the object object has the attribute name, the value of the attribute is returned; if the object does not have the attribute name, and the default value default is specified, the default value is returned; if the object does not have the attribute name, and the default value is not specified value, an AttributeError exception will be triggered.
The following are some examples of use of the getattr() function:
Example 1:
class Car: def __init__(self, brand, color, price): self.brand = brand self.color = color self.price = price car = Car("Toyota", "Blue", 20000) # 使用getattr获取对象属性值 brand = getattr(car, "brand") color = getattr(car, "color") price = getattr(car, "price") print(brand) # 输出:Toyota print(color) # 输出:Blue print(price) # 输出:20000
Example 2:
person = { "name": "Alice", "age": 25, "email": "alice@example.com" } # 使用getattr获取字典的value值 name = getattr(person, "name") # 等同于 person["name"] age = getattr(person, "age") # 等同于 person["age"] email = getattr(person, "email") # 等同于person["email"] print(name) # 输出:Alice print(age) # 输出:25 print(email) # 输出:alice@example.com
Example 3:
class Animal: def __init__(self, name): self.name = name dog = Animal("Dog") cat = Animal("Cat") lion = Animal("Lion") animals = [dog, cat, lion] for animal in animals: # 动态获取对象的属性值 name = getattr(animal, "name") print(name) # 输出:Dog Cat Lion
Through the above examples, we can see the flexibility and practicality of the getattr() function. It can dynamically obtain attribute values without knowing the object's attribute name. This flexibility is very useful when writing code.
Summary:
getattr() function is a practical built-in function that is often used in Python programming. Its usage is concise and clear, and the attribute value of the object can be obtained through the attribute name. When dealing with dynamic objects, the getattr() function can provide great convenience and flexibility. Therefore, it is necessary for us to be proficient in the usage of the getattr() function so that it can be used flexibly in actual programming.
The above is the detailed content of Introduction to Python functions: usage and examples of getattr function. For more information, please follow other related articles on the PHP Chinese website!