I feel like I don't understand how polymorphism works in Python. Here is something I put together.
class _Tag(object):
def __init__(self):
#DisjointedTag and JoinedTag will bypass __init__.
#Also, self will not be defined within this class.
#Bottom line, this class is just for inheritance.
raise NotImplementedError;
def join_attributes(self):
self.joined_pieces=''.join(self.funct_pieces);
self.__class__=JoinedTag;
def to_disjointed(self):
self.__class__=DisjointedTag;
def add_attribute(self, attribute, value):
self.funct_pieces.insert(
-1, ' {}="{}"'.format(attribute, value)
);
self.to_disjointed();
class Tag(_Tag):
def __init__(self, name):
self.funct_pieces=[
i.format(name) for i in ['<{0}', '>{{}}</{0}>']
];
self.joined_pieces='';
def __call__(self, contents):
self.join_attributes();
return self(contents);
class JoinedTag(_Tag):
def __call__(self, contents):
return self.joined_pieces.format(contents);
class DisjointedTag(_Tag):
#JoinedTag.__call__ has 1 mandatory parameter so this also needs one.
def __call__(self, place_holder):
raise TypeError(
'{} is disjointed because attributes were added to it.'.\
format(self)
);
Here is an example:
>>> p=Tag('p')
>>> p('hi')
'<p>hi</p>'
>>> p.add_attributes('align', 'left')
>>> p.join_attributes();
>>> p('hi')
'<p align="left">hi</p>'
I could have joined the attributes on every call but that would waste time. The code I made has no if
statements, so it should be more readable according to the philosophy of polymorphism. However, it is very hard to read. I figure I've done something wrong or I'm not used to reading polymorphic code.
SyntaxError: invalid syntax
when I try to run your code. At Code Review we review working code. \$\endgroup\$add_attribute
method definition is missing adef
keyword. \$\endgroup\$self.__class__
that way lies dragons. Do you really need separate classes forJoinedTag
andDisjointededTag
? A flag would seem fine. \$\endgroup\$