Python: Inheritance of a class attribute (list)
Posted
by Sano98
on Stack Overflow
See other posts from Stack Overflow
or by Sano98
Published on 2010-03-21T19:00:55Z
Indexed on
2010/03/21
19:21 UTC
Read the original article
Hit count: 586
Hi everyone,
inheriting a class attribute from a super class and later changing the value for the subclass works 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 Archer's value, Unit's value remains untouched.
Now, if the inherited value is a list, the shallow copy effect strikes 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 the super class?
Many thanks
Sano
© Stack Overflow or respective owner