python __getattr___python:__getattr__() 和 __getattribute__()

关于__getattr__

object.__getattr__(self, name)

Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self). name is the attribute name. This method should return the (computed) attribute value or raise an AttributeError exception.

Note that if the attribute is found through the normal mechanism, __getattr__() is not called.

(This is an intentional asymmetry between __getattr__() and __setattr__().) This is done both for efficiency reasons and because otherwise __getattr__() would have no way to access other attributes of the instance. Note that at least for instance variables, you can fake total control by not inserting any values in the instance attribute dictionary (but instead inserting them in another object). See the __getattribute__() method below for a way to actually get total control in new-style classes.

关于__get__getattribute__

object.__getattribute__(self, name)

Called unconditionally to implement attribute accesses for instances of the class. If the class also defines __getattr__(), the latter will not be called unless __getattribute__() either calls it explicitly or raises an AttributeError. This method should return the (computed) attribute value or raise an AttributeError exception. In order to avoid infinite recursion in this method, its implementation should always call the base class method with the same name to access any attributes it needs, for example, object.__getattribute__(self, name).

Note This method may still be bypassed when looking up special methods as the result of implicit invocation via language syntax or built-in functions.

例子: __getattr__示例:

class Test(object):

def __init__(self,name):

self.name = name

def __getattr__(self, value):

if value == 'address':

return 'China'

if __name__=="__main__":

test = Test('letian')

print test.name

print test.address

test.address = 'Anhui'

print test.address 运行结果:

letian

China

Anhui 如果是调用了一个类中未定义的方法,则__getattr__也要返回一个方法,例如:

class Test(object):

def __init__(self,name):

self.name = name

def __getattr__(self, value):

return len

if __name__=="__main__":

test = Test('letian')

print test.getlength('letian') 运行结果:

6 __getattribute__示例:

class Test(object):

def __init__(self,name):

self.name = name

def __getattribute__(self, value):

if value == 'address':

return 'China'

if __name__=="__main__":

test = Test('letian')

print test.name

print test.address

test.address = 'Anhui'

print test.address 运行结果:

None

China

China

参考: Data model:

http://docs.python.org/2/reference/datamodel.html

Overwriting __getattr__ makes help(…) fail with TypeError:

http://stackoverflow.com/questions/5157746/overwriting-getattr-makes-help-fail-with-typeerror

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
`__getattr__`和`__getattribute__`是Python中特殊的方法,用于处理对象的属性访问和获取。 `__getattr__`用于在对象实例的属性不存在时被调用,通常在动态获取属性的情况下使用。当我们尝试访问一个对象上不存在的属性时,Python解释器会自动调用`__getattr__`方法。我们可以在这个方法中定义对不存在属性的处理逻辑,比如返回默认值或者触发异常。 下面是一个示例: ``` class MyClass: def __getattr__(self, name): return f"Attribute {name} does not exist." obj = MyClass() print(obj.some_attr) # Output: Attribute some_attr does not exist. ``` `__getattribute__`用于在对象实例的属性被访问时被调用。与`__getattr__`不同,`__getattribute__`会在所有属性访问上被调用,无论属性是否存在。我们可以通过在`__getattribute__`方法中自定义属性访问的行为,比如在访问属性前执行一些操作或返回特定的值。 下面是一个示例: ``` class MyClass: def __getattribute__(self, name): print(f"Accessing attribute {name}") return super().__getattribute__(name) obj = MyClass() print(obj.some_attr) # Output: # Accessing attribute some_attr # None ``` 注意,使用`__getattribute__`时需要谨慎,因为在方法内部访问同个实例的其他属性时可能会触发无限递归调用。在这种情况下,可以通过使用`super()`来避免无限递归。 综上所述,`__getattr__`和`__getattribute__`是Python中用于处理对象属性访问和获取的特殊方法,分别用于处理不存在属性和所有属性的访问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值