[Tutor] help with refactoring needed -- which approach is morePythonic?

Jeremy Jones zanesdad at bellsouth.net
Fri Feb 11 17:27:37 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.
>
> Does this make sense?

I think so.  I haven't tested this (pseudo) code which I took from your 
above post and just modified it, but I think you want something like this:

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(self) #when you create a node, pass in 
the parent object like this
                 if line == NodeEndTag:
                    self.nodes.append(node)
                 node.append(line)

       class Node:
         def __init__(self, parent, lines=[]):
              self.lines = lines
              self.parent = parent #and store the parent like this
         def append(self,item):
              self.lines.append(item)
         def parse(self):
              # your parsing method here.
         def show_siblings(self):
              print self.parent.nodes # and you can access the parent 
kinda like this.

You don't want to get too carried away with something like this, 
though.  You may want to read up on the Law of Demeter.  This (in my 
opinion) is fine, though.

>
> 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
>
Jeremy Jones


More information about the Tutor mailing list