我一直在阅读描述类继承,抽象基类甚至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)
我重新路由是远远没有达到最佳,因为只有调用()函数获得通过的number_of_edges。给Shape添加这样的东西并不能解决问题:
def __getattr__(self, *args):
return underlying_class.__getattr__(*args)
我在做什么错了?整个想法是否被严格执行?任何帮助不胜感激。
'__getattr__'仅适用于新样式类的作品。这意味着你的类必须是'object'的子类。 – 2010-06-19 18:07:29
你正在做的事情也被称为具有虚拟构造函数的类(而不是“虚拟类”)。参见相关的问题[_什么是类工厂?](http://stackoverflow.com/questions/2526879/what-exactly-is-a-class-factory) – martineau 2016-12-02 03:03:22