我正在尝试弄清楚如何__setattr__
使用类上的装饰器来更改类的功能,但是在尝试访问self
替换__setattr__
. 如果我将问题行更改为 not access self
,例如将其替换为val = str(val)
,我会得到预期的行为。
我在这里的其他问题中看到了类似的问题,但他们使用了不同的方法,其中一个类被用作装饰器。我下面的方法感觉不那么复杂,所以如果可能的话,我很乐意保持这种状态。
为什么a
不能在self
/foo
我期望的地方定义?
# Define the function to be used as decorator
# The decorator function accepts the relevant fieldname as argument
# and returns the function that wraps the class
def field_proxied(field_name):
# wrapped accepts the class (type) and modifies the functionality of
# __setattr__ before returning the modified class (type)
def wrapped(wrapped_class):
super_setattr = wrapped_class.__setattr__
# The new __setattr__ implementation makes sure that given an int,
# the fieldname becomes a string of that int plus the int in the
# `a` attribute
def setattr(self, attrname, val):
if attrname == field_name and isinstance(val, int):
val = str(self.a + val) # <-- Crash. No attribute `a`
super_setattr(self, attrname, val)
wrapped_class.__setattr__ = setattr
return wrapped_class
return wrapped
@field_proxied("b")
class Foo(object):
def __init__(self):
self.a = 2
self.b = None
foo = Foo()
# <-- At this point, `foo` has no attribute `a`
foo.b = 4
assert foo.b == "6" # Became a string