3
考慮以下Python代碼:的Python:超載__getattr__和性能,使得__setattr__正常工作
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
<__main__.Foo object at 0x819410>
>>> b.foo.value
'value: foo'
>>> b.foo.value = '2'
>>> b.foo.value
'value: 2'
>>> b.value
'value: 2'
>>> b.value = '3'
>>> b.value
'3'
這最後一部分,我希望它是「值:3」,而不是「3」,因爲現在我的屬性'值'現在是一個屬性。
是否有可能,如果是我會怎麼做。
那麼我該如何實現這樣的__setattr__。我試過但不知道如何正確地做到這一點。謝謝Martijn! – glouie
@glouie:增加了一個例子'__seta ttr__'爲你。 –
這樣做!非常感謝! – glouie