我一直在閱讀描述類繼承,抽象基類甚至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