What I've succeeded to do so far:
I've made an elem
class to represent html elements (div
, html
, span
, body
, etc.).
I'm able to derivate this class like this to make subclasses for each element:
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)
And it works pretty well.
But I have to write this for each subclass declaration, and that's pretty repetitive and redundant if I want to do every HTML tag type.
So I was trying to make a make_elem()
function that would make my class by taking the corresponding tag name as a string parameter.
So instead of the previous class definition, I would simply have something like this:
head = make_elem_class("head")
Where I'm stuck
This function should create a class. And the __init__()
method from this class should call the __init__()
method from the class it inherits from.
I tried to make this make_elem_class()
function and it looked like this :
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})
But when running html = make_elem_class('html')
, then html("html element")
I get the following error:
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
I guess that it has something to do with the empty super()
call, so I tried with super(elem, self)
instead. But it obviously doesn't work better.
How could I achieve this?
NB : If I remove the "__init__":init
from the dictionnary in the type()
call, it works fine but the tag isn't correctly set in my elem. I've also tried to directly pass {"tag":name}
to type()
but it didn't work either.