Search code examples
pythonpython-3.xclassinheritanceclass-variables

Prevent sharing of class variables with base class in Python


I have the following situation in Python 3:

class A:
    d = {}

class B(A):  pass
class C(A):  pass

I work with the classes only, no instances get created. When I access B.d I will get a shared reference to A.d. That's not what I want. I would like to have each class which inherits A have its own d which is set to a dictionary. d is an implementation detail to A. All access to d is done in the code of A. Just B's d should not be identical to A's d.

With instances, I would create that dictionary in the __init__() function. But in my case I work with the classes only.

Is there a standard way to achieve this (EDIT: without changing the implementation of the subclasses B and C)? Is there something analog to __init__() which gets called for (or in) each derived class at the time of deriving?


Solution

  • I found a solution myself using a metaclass:

    class M(type):
      def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.d = {}
    
    class A(metaclass=M): pass
    

    Then one can create subclasses of A which all have their own d attribute:

    class B(A): pass
    
    B.d is A.d
    False