python - Class attribute overriding: keep parent class changes -


i want 2 class. class default class attribute , class b (child class) override class attribute. if class attribute definition changed developper, don't want write again b class attribute.

exemple: simple override:

class animal:     actions = {}  class dog(animal):     actions = {'bite': 1} 

if day, animal modified this:

class animal:     actions = {'bleed': 1} 

dog class have rewrited. prevent parent class update:

python 3.4.0 (default, apr 11 2014, 13:05:18)  [gcc 4.8.2] on linux type "help", "copyright", "credits" or "license" more information. >>> class a: ...   d = {} ...   @classmethod ...   def c(cls): ...     print(cls.d) ...  >>> class b(a): ...   d = a.d.copy() ...   d.update({0: 1}) ...  >>> b.c() {0: 1} >>> a.c() {} 

is way it? or there more "python way" it?

attribute copying in class method

by using copy ensuring a's d, no matter what/who defines it, starting point before b extends it.

class a:     d = {}     @classmethod     def c(cls):         print (cls.d)  class b(a):     d = a.d.copy()     d.update({0:1})  b.c() a.c() 

output

{0: 1} {} 

developer changes a @ later time, b gets a without touching b's definition.

class a:     d = {2:3}     @classmethod     def c(cls):         print (cls.d)  class b(a):     d = a.d.copy()     d.update({0:1})  b.c() a.c() 

output

{0: 1, 2: 3} {2: 3} 

warning: if d contains other objects inside it, may want use copy.deepcopy, otherwise first "level" copied, others objects references original (this caused me a lot of grief once, before knew it!).

inheriting in instance method

the dictionary copying pythonic in sense clear b gets a , extends it, since creating instances in use case (of dog), these classes might missing concept of class instance using __init__ method. allow have multiple bs potentially unique ds.

here example of class definitions instance in mind

class a:     def __init__(self):         self.d = {}     def c(self):         print (self.d)  class b(a):     def __init__(self):         a.__init__(self)         self.d.update({0:1})  # create instances of each class = a() b1 = b()  b2 = b()    # call each instance's c method b1.c() b2.c() a.c()  # can update on fly without affecting other! a.d.update({2:3}) b1.d.update({4:5}) b2.d.update({7:8}) b1.c() b2.c() a.c() 

output

{0: 1} {0: 1} {} {0: 1, 4: 5} {0: 1, 7: 8} {2: 3}