python的getattr和setattr_Python:重载getattr和属性,使setattr正常工作

考虑以下python代码:class Foo(object):

def __init__(self, value):

self._value = value

@property

def value(self):

return "value: {v}".format(v=self._value)

@value.setter

def value(self, value):

self._value = value

class Bar(object):

def __init__(self):

self.foo = Foo('foo')

def __getattr__(self, attr, *args, **kwargs):

"""

Intercepts attribute calls, and if we don't have it, look at the

webelement to see if it has the attribute.

"""

# Check first to see if it looks like a method, if not then just return

# the attribute the way it is.

# Note: this has only been tested with variables, and methods.

if not hasattr(getattr(self.foo, attr), '__call__'):

return getattr(self.foo, attr)

def callable(*args, **kwargs):

'''

Returns the method from the webelement module if found

'''

return getattr(self.foo, attr)(*args, **kwargs)

return callable

>>> b = Bar()

>>> b.foo

>>> b.foo.value

'value: foo'

>>> b.foo.value = '2'

>>> b.foo.value

'value: 2'

>>> b.value

'value: 2'

>>> b.value = '3'

>>> b.value

'3'

最后一部分,我希望它是'value:3'而不是'3',因为现在我的属性'value'现在变成了一个属性。在

有可能吗?如果是的话,我会怎么做呢。在

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值