Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/maven/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 强制装饰器仅扩展继承类上的静态字段,即使未显式重写_Python_Inheritance_Static_Python Decorators - Fatal编程技术网

Python 强制装饰器仅扩展继承类上的静态字段,即使未显式重写

Python 强制装饰器仅扩展继承类上的静态字段,即使未显式重写,python,inheritance,static,python-decorators,Python,Inheritance,Static,Python Decorators,我正在编写一个用于继承类的decorator,该decorator应该在基类的字段列表中添加一些值。我发现的问题是,除非类定义显式列出该字段,否则装饰器最终会修改基类,而基类又会将值添加到从该类继承的所有其他类中。看起来好像没有在类上定义字段,而是在基类上操作字段。有没有办法强制继承的类拥有自己的可变字段(以与基字段相同的值开头),而不影响基类字段的值 可以肯定的是,我可以通过不做我正在做的事情来找到解决这个问题的方法,但是我想知道是否有一种方法可以让我想做的事情起作用,最好是通过修改装饰器。除

我正在编写一个用于继承类的decorator,该decorator应该在基类的字段列表中添加一些值。我发现的问题是,除非类定义显式列出该字段,否则装饰器最终会修改基类,而基类又会将值添加到从该类继承的所有其他类中。看起来好像没有在类上定义字段,而是在基类上操作字段。有没有办法强制继承的类拥有自己的可变字段(以与基字段相同的值开头),而不影响基类字段的值

可以肯定的是,我可以通过不做我正在做的事情来找到解决这个问题的方法,但是我想知道是否有一种方法可以让我想做的事情起作用,最好是通过修改装饰器。除了一个解决方案,解释一下为什么会这样以及我对python、静态字段继承和decorator不了解的地方会很好

我在下面给出了一些基本情况请注意,如果扩展类单独使用,则此打印行是正确的,而不是像图中所示那样与它们并排使用。

def add_values(cls):
    cls.my_list.append(1)
    return cls

class Base(object):
    my_list = []

### in the following case, the definition of Base actually changes
@add_values
class Extension1(Base):

    def append_1(self):
        self.my_list.append(1)
        print(self.my_list) ### this prints [1, 1]
        print(Base.my_list) ### this prints [1, 1]


### in this case, the definition of Base is fine and it only modifies
### the field on this class definition, which is what I'd expect.
@add_values
class Extension2(Base):
    my_list = []

    def append_1(self):
        self.my_list.append(1)
        print(self.my_list) ### this prints [1, 1]
        print(Base.my_list) ### this prints []

类不会复制从基类继承的值。它只是一个属性查找系统,搜索它们之前定义的位置。您可能应该做的是将
my_list
类变量的变异更改为非变异版本:

def add_values(cls):
    cls.my_list = cls.my_list + [1]  # like cls.my_list.append(1), but makes a new list
    return cls
这将创建一个添加了1的新列表,并将其绑定到
add_values
,无论您是修饰基类还是派生类