【发布时间】:2011-03-05 19:52:27
【问题描述】:
我一直在阅读描述类继承、抽象基类甚至 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的子类。 -
您尝试做的也被称为具有虚拟构造函数的类(而不是“虚拟类”)。查看相关问题What exactly is a Class Factory?
标签: python class inheritance virtual abstract