我已經成功至今做的事:
我已經做了一個elem
類來表示HTML元素(div
,html
,span
,body
等)。混合型(),並使用超()自定義__init __().__的init()__
我能夠衍生物該類這樣使子類的每個元素:
class elem:
def __init__(self, content="", tag="div", attr={}, tag_type="double"):
"""Builds the element."""
self.tag = tag
self.attr = attr
self.content = content
self.tag_type = tag_type
class head(elem):
"""A head html element."""
def __init__(self, content=None, **kwargs):
super().__init__(tag="head", content=content, **kwargs)
而且它工作得很好。
但是我必須爲每個子類聲明寫這個,如果我想要做每一個HTML標記類型,那麼這是相當重複和冗餘的。
所以我試圖做一個make_elem()
函數,通過將相應的標籤名稱作爲字符串參數來創建我的類。
因此,而不是以前的類定義,我只想有這樣的事情:
head = make_elem_class("head")
如果我堅持
這個函數應該創建一個類。而這個類的__init__()
方法應該從它繼承的類中調用__init__()
方法。
我試圖讓這個make_elem_class()
功能,它看起來像這樣:運行html = make_elem_class('html')
時
def make_elem_class(name):
"""Dynamically creates the class with a type() call."""
def init(self, content=None, **kwargs):
super().__init__(tag=name, content=None, **kwargs)
return type(name, (elem,), {"__init__" : init})
但是,然後html("html element")
我得到以下錯誤:
Traceback (most recent call last):
File "elements.py", line 118, in <module>
html("html element")
File "elements.py", line 20, in init
super().__init__(tag=name, content=None, **kwargs)
TypeError: object.__init__() takes no parameters
我想它有什麼與空的super()
打電話,所以我試着用super(elem, self)
來代替。但它顯然不會更好。
我怎麼能做到這一點?
注意:如果我從type()
呼叫dictionnary刪除"__init__":init
,它工作正常,但標籤不正確我ELEM設置。我也試圖直接通過{"tag":name}
到type()
,但它也沒有工作。
你能製作一個簡化的elem類嗎?我也不能重現你的確切異常,我得到'RuntimeError:super():__class__ cell not found'。你可能在某處使用'make_elem_class'作爲靜態或類方法嗎? –
或者,您是否可能在某處設置了__class__ = elem? –
@MartijnPieters當然!我編輯了我的帖子,'__init __()'方法完成。在我的代碼中沒有'__class__ = elem'。 – vmonteco