__getattr__(self, name)
时间: 2024-09-20 08:10:38 浏览: 53
`__getattr__(self, name)` 是Python中一种特殊的方法,它在尝试访问一个对象的属性(通过点操作符 `.` 或者 `[]` 访问)而这个属性不存在时被调用。这是Python中动态属性查找的一个机制,允许自定义类处理未预期的属性请求。
当你试图访问一个实例的 `name` 属性,如果该对象没有直接定义名为 `name` 的属性,Python会查找该类型的 `__getattr__` 方法。如果找到了,这个方法会被调用,并将属性名作为 `name` 参数传递进去。你可以在这个方法里做各种事情,比如提供默认值、检查属性是否合法,甚至连接到远程服务器获取属性值。
一个典型的例子可能是装饰器或者缓存策略,或者是为了模拟某种复杂的数据结构:
```python
class MyClass:
def __getattr__(self, name):
# 这里可以读取数据库,网络或其他地方的信息
return self._fetch_data_from_external_source(name)
my_instance = MyClass()
print(my_instance.non_existent_attribute) # 如果没有这个属性,将会调用 _fetch_data_from_external_source('non_existent_attribute')
```
相关问题
__get__和__getattr__区别
`__get__` 和 `__getattr__` 都是 Python 中的特殊方法,但它们的作用不同。
`__get__` 通常与描述器一起使用,用于控制属性的获取行为。当我们访问一个对象的属性时,如果这个属性有对应的描述器对象,就会调用这个描述器对象的 `__get__` 方法来获取属性的值。如果一个类定义了一个描述器,那么这个描述器实例的 `__get__` 方法将会被调用来获取属性值。
`__getattr__` 是一个对象的特殊方法,用于在访问一个对象的属性时,如果这个属性不存在,就会自动调用 `__getattr__` 方法,并返回一个默认值或抛出一个异常。`__getattr__` 方法接收一个参数 `name`,表示访问的属性名,如果对象有这个属性,则直接返回属性值;如果没有,可以返回一个默认值或者抛出一个 `AttributeError` 异常。
下面是一个示例来说明这两个方法的不同:
```python
class Descriptor:
def __get__(self, instance, owner):
print("Getting the attribute...")
return instance._attr
class MyClass:
attr = Descriptor()
def __init__(self, value):
self._attr = value
def __getattr__(self, name):
if name == 'non_existent_attr':
return 'default_value'
else:
raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'")
```
在上面的例子中,我们定义了一个描述器 `Descriptor`,并将其作为 `MyClass` 中属性 `attr` 的值。`MyClass` 中还定义了一个 `__getattr__` 方法,用于处理不存在的属性访问。当我们访问 `MyClass` 实例的属性 `attr` 时,会调用 `Descriptor` 中的 `__get__` 方法,从而打印出 "Getting the attribute..." 并返回 `_attr` 的值。当我们访问 `MyClass` 实例的不存在的属性 `non_existent_attr` 时,会调用 `__getattr__` 方法,并返回默认值 "default_value"。
```python
>>> obj = MyClass(10)
>>> obj.attr
Getting the attribute...
10
>>> obj.non_existent_attr
'default_value'
>>> obj.unknown_attr
AttributeError: 'MyClass' object has no attribute 'unknown_attr'
```
在上面的例子中,我们首先创建了一个 `MyClass` 的实例 `obj`,并将其初始化为 10。接着我们访问了 `obj` 的属性 `attr`,这会打印出 "Getting the attribute..." 并返回 10。然后我们访问了 `obj` 的不存在的属性 `non_existent_attr`,这会直接返回默认值 "default_value"。最后我们访问了 `obj` 的未知属性 `unknown_attr`,这会触发 `__getattr__` 方法,并抛出一个 `AttributeError` 异常。
总之,`__get__` 和 `__getattr__` 的作用不同。`__get__` 通常用于描述器中控制属性的获取行为,而 `__getattr__` 用于处理不存在的属性访问。
self.__getattr__
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'
```
阅读全文
相关推荐















