I have a Base class that stores some basic methods, attributes, etc in it and I've got a Mixin that I'd like to share across one or more sub-classes of Base. Something like this:
class Base(object): pass
class Mixin(object):
# IMPORTANT: cache _x locally on Mixin to only compute for all subclasses
_x = None
@property
def x(self):
if self._x is None:
print 'reset _x'
self._x = 2
return self._x
class A(Base, Mixin): pass
class B(Base, Mixin): pass
Importantly, I want to cache the _x variable on the Mixin so it is only computed once across all subclasses A, B, etc. --- it takes a long time to compute this value. Oddly, this doesn't appear to work as I expected in python:
a = A()
b = B()
print 'calling a.x'
a.x
print 'calling a.x'
a.x
print 'calling b.x'
b.x
print 'calling b.x'
b.x
This prints out reset _x twice --- once for the first call to a.x, which I expected, and again for the first call to b.x, which I didn't expect. My understanding of python class attributes was that they are stored once on a per-class basis. Can anyone explain what is going on here?
Are there better patterns for having _x cached locally on Mixin?