【发布时间】:2016-02-21 14:03:25
【问题描述】:
考虑以下最小问题:
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()
所以本质上 NormalizedVector 对象与 Vector 对象相同,但增加了标准化。
是否可以向 Vector 添加一个方法,以便每当调用 normalize 方法时,对象就会自动子类化为 NormalizedVector?
我知道我可以使用abstract factory pattern,但这只有在对象在创建时被子类化时才有效:我希望能够对之前已经创建的对象进行子类化。
我发现 some solutions 基于重新分配 __ 类 __ 方法,但不鼓励这样做。我愿意将上面的模式修改为更“Pythonic”的模式。
【问题讨论】:
-
为什么不只使用带有布尔
normalized实例属性的 Vector 类?
标签: python object inheritance casting subclass