[Tutor] help with refactoring needed -- which approach
is morePythonic?
Kent Johnson
kent37 at tds.net
Fri Feb 11 17:34:02 CET 2005
Brian van den Broek wrote:
> Alan Gauld said unto the world upon 2005-02-10 02:58:
>
>> Pseudo code:
>> class Body:
>> def __init__(self,content):
>> self.contents = contents
>> self.nodes = []
>>
>> def parse(self):
>> for line in self.contents:
>> if line == NodeStartTag:
>> node = Node()
>> if line == NodeEndTag:
>> self.nodes.append(node)
>> node.append(line)
>>
>> class Node:
>> def __init__(self,lines=[]):
>> self.lines = lines
>> def append(self,item):
>> self.lines.append(item)
>> def parse(self):
>> # your parsing method here.
>
>
> Hi all,
>
> YAQ (Yet Another Question):
>
> Following the general pattern, I end up with a Body object which has an
> attribute .nodes that consists of a list of Node objects.
>
> So, something like:
>
> My Example Body
> Node List
> Node the first
> Node the second
>
> Is there any way to make methods of the Node class access attributes of
> `parents' of instances? I would like a Node instance such as Node the
> first above to be aware just what it is a node of and what its siblings
> are.
You have to tell it the parent. ("Explicit is better than implicit.") For example you could pass a
reference to Body to the Node in the constructor:
def parse(self):
for line in self.contents:
if line == NodeStartTag:
node = Node(self) # HERE
if line == NodeEndTag:
self.nodes.append(node)
node.append(line)
In general I think this is a bad design. I try to avoid telling components about their parents in
any kind of containment hierarchy. If the component knows about its parent, then the component can't
be reused in a different context and it can't be tested without creating the expected context.
Is there another way you could accomplish what you want?
Kent
>
> Does this make sense?
>
> Best to all,
>
> Brian vdB
>
> PS Thanks for the reply to my venting question, Kent.
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
More information about the Tutor
mailing list