self.__getattr__
时间: 2023-10-25 20:08:32 浏览: 102
self.__getattr__ is a special method in Python that is used to define what happens when an attribute that does not exist is accessed on an object. It is called automatically by Python when an attribute lookup fails, and it can be used to dynamically generate attributes or to redirect attribute access to other objects.
For example, let's say we have a class called Person that has a dictionary attribute called info. We can use __getattr__ to allow accessing the keys of the info dictionary directly on the Person object:
```
class Person:
def __init__(self, name):
self.name = name
self.info = {'age': 30, 'city': 'New York'}
def __getattr__(self, name):
if name in self.info:
return self.info[name]
else:
raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'")
```
Now we can create a Person object and access the age and city attributes directly:
```
p = Person('John')
print(p.age) # Output: 30
print(p.city) # Output: New York
```
If we try to access an attribute that doesn't exist in the info dictionary, we'll get an AttributeError:
```
print(p.gender) # Output: AttributeError: 'Person' object has no attribute 'gender'
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)