0

我正在尝试弄清楚如何__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
4

1 回答 1

1

问题很简单,你只需要换行。

def setattr(self, attrname, val):
    if attrname == field_name and isinstance(val, int):
        val = str(self.a + val)
    super_setattr(self, attrname, val)  # changed line

原因是,在您原来的方法中,您只会调用super_setattrwhen attrname == field_name。所以self.a = 2in__init__根本不起作用"a" != "b"

于 2018-05-16T07:01:54.570 回答