我一直在阅读描述类继承、抽象基类甚至Python接口的文档。但没有接缝是我想要的。也就是说,一种构建虚拟类的简单方法。当虚拟类被调用时,我希望它根据给定的参数实例化一些更具体的类,并将其返回调用函数。目前,我有一个将调用重新路由到虚拟类的概要方法,将其向下路由到基础类。
想法如下:
class Shape:
def __init__(self, description):
if description == "It's flat": self.underlying_class = Line(description)
elif description == "It's spiky": self.underlying_class = Triangle(description)
elif description == "It's big": self.underlying_class = Rectangle(description)
def number_of_edges(self, parameters):
return self.underlying_class(parameters)
class Line:
def __init__(self, description):
self.desc = description
def number_of_edges(self, parameters):
return 1
class Triangle:
def __init__(self, description):
self.desc = description
def number_of_edges(self, parameters):
return 3
class Rectangle:
def __init__(self, description):
self.desc = description
def number_of_edges(self, parameters):
return 4
shape_dont_know_what_it_is = Shape("It's big")
shape_dont_know_what_it_is.number_of_edges(parameters)
我的重新路由远不是最佳的,因为只传递了对_edges()函数个数的调用。在形状上添加这样的东西也不需要缝合来完成这个技巧:
def __getattr__(self, *args):
return underlying_class.__getattr__(*args)
我做错了什么?整个想法实施得不好吗?非常感谢您的帮助。
最佳答案
我更喜欢在工厂里做:
def factory(description):
if description == "It's flat": return Line(description)
elif description == "It's spiky": return Triangle(description)
elif description == "It's big": return Rectangle(description)
或:
def factory(description):
classDict = {"It's flat":Line("It's flat"), "It's spiky":Triangle("It's spiky"), "It's big":Rectangle("It's big")}
return classDict[description]
从形状继承类
class Line(Shape):
def __init__(self, description):
self.desc = description
def number_of_edges(self, parameters):
return 1