Python: Inheriting a Class Attribute (List)

inheriting the class attribute from the superclass and then changing the value for the subclass works just fine:

class Unit(object):
    value = 10

class Archer(Unit):
    pass

print Unit.value
print Archer.value

Archer.value = 5

print Unit.value
print Archer.value

leads to the output:
10
10
10
5
which is just fine: Archer inherits the value from Unit, but when I change the value of Archer, the value of Unit remains untouched.

Now, if the inherited value is a list, the effect of the shallow copy is hit and the value of the superclass is also affected:

class Unit(object):
    listvalue = [10]

class Archer(Unit):
    pass

print Unit.listvalue
print Archer.listvalue

Archer.listvalue[0] = 5

print Unit.listvalue
print Archer.listvalue

Output:
10
10
5
5

Is there a way to "deep copy" a list when inheriting it from a superclass?

Thanks a lot Sano

+5
3

, .

Unit.value Archer.value - , . Archer.value = 5, Acher.value.

, Archer.list.

, .

+12

, Unit, , , , - .

class UnitMeta(type):
    def __init__(self, *args):
        super(UnitMeta, self).__init__(*args)
        self.listvalue = [10]

class Unit(object):
    __metaclass__ = UnitMeta
    pass

class Archer(Unit):
    pass

print Unit.listvalue
print Archer.listvalue

Archer.listvalue[0] = 5

print Unit.listvalue
print Archer.listvalue

:

[10]
[10]
[10]
[5]

, ( dicts), Unit

class UnitMeta(type):
    def __init__(self, *args):
        super(UnitMeta, self).__init__(*args)
        for superclass in self.__mro__:
            for k,v in vars(superclass).items():
                if isinstance(v, (list, dict, )):
                    setattr(self, k, type(v)(v))

class Unit(object):
    __metaclass__ = UnitMeta
    listvalue = [10]

class Archer(Unit):
    pass
+7

Archer:

class Archer(Unit):
    listvalue = Unit.listvalue[:]
0

All Articles