Consider the following minimal problem:
from math import sqrt
class Vector(object):
def __init__(self, x, y, z):
self.v = [x, y, z]
def normalize(self):
x, y, z = self.v
norm = sqrt(x**2 + y**2 + z**2)
self.v = [x/norm, y/norm, z/norm]
# other methods follow
class NormalizedVector(Vector):
def __init__(self, x, y, z):
super(Vector, self).__init__(x, y, z)
self.normalize()
So essentially NormalizedVector objects are the same as Vector objects but with the added normalization.
Would it be possible to add a method to Vector so that whenever the normalize method is called the object is automatically subclassed to NormalizedVector?
I know that I could be using the abstract factory pattern, but this would only work if objects are subclassed at creation: I would like to be able to subclass objects that have already been created previously.
I have found some solutions based on reassigning the __ class __ method, but these are discouraged. I am willing to modify the pattern above to a one that it is more "Pythonic".
normalizedinstance attribute?