Skip to main content
 首页 » 编程设计

python之为什么修改类属性不会修改 Python 中的对象属性

2024年11月01日8kenshinobiy

因此,如下面的代码片段所示,我无法完全理解 Python 是如何访问类变量的。

class Test(): 
    var = 1 
 
obj = Test() 
obj2 = Test() 
print(Test.var, '\t',obj.var, '\t', obj2.var) 
 
obj.var += 1 
print(Test.var, '\t',obj.var, '\t', obj2.var) 
 
Test.var += 5 
print(Test.var, '\t',obj.var, '\t', obj2.var) 

给出以下输出:

1        1       1  # Makes sense 
1        2       1  # Also makes sense 
6        2       6  # I would expect obj.var to become '7' 

obj.var 保持不变。这是否意味着修改 obj.var 创建了一个现在独立于类属性 var 的对象特定变量?

请您参考如下方法:

混淆可能在 obj.var += 1 指令中。

这等同于 obj.var = obj.var + 1。右侧在对象上找不到 var,因此委托(delegate)给类。然而,左侧将结果存储在对象上。从那时起,在对象上查找 var 将不再委托(delegate)给类属性。

>>> class Test(): 
>>>    var = 1 
>>> Test.__dict__ 
mappingproxy({'__module__': '__main__', 
              'var': 1, 
              '__dict__': <attribute '__dict__' of 'Test' objects>, 
              '__weakref__': <attribute '__weakref__' of 'Test' objects>, 
              '__doc__': None}) 
>>> obj = Test() 
>>> obj.__dict__ 
{} 
>>> obj.var += 1 
>>> obj.__dict__ 
{'var': 2} 

如果你删除对象属性然后类属性再次暴露:

>>> Test.var += 5 
>>> obj.var 
2 
>>> del obj.var 
>>> obj.var 
6 

来自 the docs 的相关位:

A class instance has a namespace implemented as a dictionary which is the first place in which attribute references are searched. When an attribute is not found there, and the instance’s class has an attribute by that name, the search continues with the class attributes.


关于您的后续问题,这是使用 data descriptors 执行您想要的操作的一种方法。 ,尽管我认为它不是很 Pythonic。特别是,在类上使用数据描述符是不常见的(如果不小心,可能会破坏东西)。

class VarDescriptorMetaclass(type): 
    """Metaclass to allow data descriptor setters to work on types.""" 
    def __setattr__(self, name, value): 
        setter = getattr(self.__dict__.get(name), '__set__') 
        return setter(None, value) if setter else super().__setattr__(name, value) 
 
class VarDescriptor(object): 
    """Data descriptor class to support updating property via both class and instance.""" 
    def __init__(self, initial_value): 
        self.value = initial_value 
    def __get__(self, obj, objtype): 
        if obj and hasattr(obj, '_value'): 
            return self.value + obj._value 
        return self.value 
    def __set__(self, obj, value): 
        if obj: 
            obj._value = value - self.value 
        else: 
            self.value = value 
    def __delete__(self, obj): 
        if obj and hasattr(obj, '_value'): 
            del obj._value 
 
class Test(metaclass=VarDescriptorMetaclass): 
    var = VarDescriptor(initial_value=1) 

这似乎可以满足您的要求:

>>> obj = Test() 
>>> obj.var 
1 
>>> obj.var += 1 
>>> obj.var 
2 
>>> Test.var += 5 
>>> Test.var 
6 
>>> obj.var 
7