As an alternative to Chris's answer implementing the memoisation suggestion for shx2's answer, I'd prefer to use a memoize decorator (the end result is still a class but it's clearer to me that the function is the interface), and also use setdefault
to simplify adding to the memo dict, and do not convert the names to string but use the tuple bases
itself as the key, simplifying the code to:
class Memoize: def __init__(self, f): self.f = f self.memo = {} def __call__(self, *args): return self.memo.setdefault(args, self.f(*args))class ParentA: def initialize(self): passclass ParentB: def initialize(self): pass@Memoizedef get_my_code(base): class MyCode(base): def initialize(self): pass return MyCodea1 = get_my_code(ParentA)a2 = get_my_code(ParentA)b1 = get_my_code(ParentB)print(a1 is a2) # Trueprint(a1 is b1) # False
(Not a good example as the code provided doesn't actually do anything other than overwrite the parent class's initialize
method...)