"parent" in a class __init__ def?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Ray Schumacher

    #1

    "parent" in a class __init__ def?

    What is the feeling on using "parent" in a class definition that
    class methods can refer to, vs. some other organization ?
    Should all relevant objects/vars just be passed into the method as needed?
    It seems like including "parent" in the class def is just like a
    class variable, which most do not recommend.

    An example:
    class LXSerial:
    def __init__(self, parent, debug=False):
    ...
    def connect(self, port, baud=9600, ptimeout=10):
    if self.debug:
    self.connectedP ort = StringIO.String IO(':A#')
    else:
    if self.parent.mod el=='LX200GPS': ptimeout = 240
    ...

    Ray


  • Larry Bates

    #2
    Re: "parent&qu ot; in a class __init__ def?

    Ray Schumacher wrote:[color=blue]
    > What is the feeling on using "parent" in a class definition that class
    > methods can refer to, vs. some other organization ?
    > Should all relevant objects/vars just be passed into the method as needed?
    > It seems like including "parent" in the class def is just like a class
    > variable, which most do not recommend.
    >
    > An example:
    > class LXSerial:
    > def __init__(self, parent, debug=False):
    > ...
    > def connect(self, port, baud=9600, ptimeout=10):
    > if self.debug:
    > self.connectedP ort = StringIO.String IO(':A#')
    > else:
    > if self.parent.mod el=='LX200GPS': ptimeout = 240
    > ...
    >
    > Ray
    >
    >[/color]
    Passing parent instance into a class is perfectly legal and is
    used extensively in modules like wxPython GUI. It isn't really
    anything like a class variable as the instance is normally
    passed not the class itself. Each instance can have different
    attributes. So if you have many parents with many children this
    can be an effective way to structure them.

    I think it depends on how deeply nested things get and how many
    parameters need to be passed. I've used it when I want to
    nest my objects more than 2 deep and I must pass around lots of
    attributes. I find it is easier to just look "upwards" into the
    parent to get the attribute than to clutter up my argument list
    passing arguments deeper and deeper into the class hierarchy.
    It can simplify the argument lists quite a bit. Maybe others can
    comment with their thoughts as well.

    -Larry Bates

    Comment

    • akameswaran@gmail.com

      #3
      Re: "parent&qu ot; in a class __init__ def?

      I'm not sure how it's a comparison to class variables. So I wouldn't
      worry about that. I think there are some advantages to having the
      parent as an instance member. Intuitively, the name lookup on
      self.parent.foo would be faster than if you passed in the object in
      question - although I haven't tested this. In short, there's nothin
      wrong with doin it - and it helps in many situations.



      Ray Schumacher wrote:[color=blue]
      > What is the feeling on using "parent" in a class definition that
      > class methods can refer to, vs. some other organization ?
      > Should all relevant objects/vars just be passed into the method as needed?
      > It seems like including "parent" in the class def is just like a
      > class variable, which most do not recommend.
      >
      > An example:
      > class LXSerial:
      > def __init__(self, parent, debug=False):
      > ...
      > def connect(self, port, baud=9600, ptimeout=10):
      > if self.debug:
      > self.connectedP ort = StringIO.String IO(':A#')
      > else:
      > if self.parent.mod el=='LX200GPS': ptimeout = 240
      > ...
      >
      > Ray[/color]

      Comment

      • bruno at modulix

        #4
        Re: "parent&qu ot; in a class __init__ def?

        akameswaran@gma il.com wrote:
        (meta : please don't top-post)[color=blue]
        > Intuitively, the name lookup on
        > self.parent.foo would be faster than if you passed in the object in
        > question[/color]


        Each dot means doing a lookup in a namespace. The more dots, the more
        lookups. And lookups do have a cost.

        --
        bruno desthuilliers
        python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
        p in 'onurb@xiludom. gro'.split('@')])"

        Comment

        • bruno at modulix

          #5
          Re: "parent&qu ot; in a class __init__ def?

          Ray Schumacher wrote:[color=blue]
          > What is the feeling on using "parent" in a class definition[/color]

          "parent" is just a name. What is the semantic for this name ? Parent
          class (ie: superclass) ? Container ? Else ?
          [color=blue]
          > that class
          > methods[/color]

          Takes care, "class method" has a very defined meaning in Python - a
          class method is a method that takes the class object - not the instance
          - as first param.
          [color=blue]
          > can refer to, vs. some other organization ?
          > Should all relevant objects/vars just be passed into the method as needed?[/color]

          There's no absolute rule about this - at most some guidelines :
          - What constitutes the state of an object should be an attribute of the
          object.
          - What is not part of the state and is only used for a given operation
          should be passed as param.
          [color=blue]
          > It seems like including "parent" in the class def is just like a class
          > variable,[/color]

          Here again, "class variable" has a well defined meaning in Python: it's
          an attribute of the class object itself, that is shared by all instances
          of the class.
          [color=blue]
          > which most do not recommend.
          >
          > An example:
          > class LXSerial:[/color]

          do yourself a favour : use new-style classes whenever possible.
          [color=blue]
          > def __init__(self, parent, debug=False):
          > ...
          > def connect(self, port, baud=9600, ptimeout=10):
          > if self.debug:
          > self.connectedP ort = StringIO.String IO(':A#')
          > else:
          > if self.parent.mod el=='LX200GPS': ptimeout = 240
          > ...[/color]

          We still don't know what's the semantic for this 'parent'. But anyway,
          having this test on self.parent.mod el smells of a design error. If the
          timeout value depends on the 'parent' object, then it's clearly a
          responsability of this parent object to know that value. Your code here
          should read:

          def connect(self, ....)
          # ...
          ptimeout = self.parent.tim eout
          # ...

          You may also want to have a look at the strategy pattern, to avoid
          cluttering your code with "if self.debug"...

          wrt/ your original question, I don't see how one could give a sound
          answer without knowing more about this "parent" object and it's
          relationship with the LXSerial class/instance of.

          --
          bruno desthuilliers
          python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
          p in 'onurb@xiludom. gro'.split('@')])"

          Comment

          • akameswaran@gmail.com

            #6
            Re: "parent&qu ot; in a class __init__ def?


            bruno at modulix wrote:[color=blue]
            > akameswaran@gma il.com wrote:
            > (meta : please don't top-post)[color=green]
            > > Intuitively, the name lookup on
            > > self.parent.foo would be faster than if you passed in the object in
            > > question[/color]
            >
            >
            > Each dot means doing a lookup in a namespace. The more dots, the more
            > lookups. And lookups do have a cost.[/color]
            hmm, intuition may not be right in this case.
            Lookups do have a cost - now I"m almost tempted to write and run a test
            for this - but the cost of each lookup is also relative to the current
            scope. I haven't looked over the implementation of the python
            interpreter - but I would hope the lookup on self would be optimized
            and trivial. The next relevant question would be is it cheaper to
            lookup self.parent or to look up a method variable, which I supsect
            would depend on the number of names in self vs. number of names in the
            method.
            [color=blue]
            >
            > --
            > bruno desthuilliers
            > python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
            > p in 'onurb@xiludom. gro'.split('@')])"[/color]

            Comment

            • bruno at modulix

              #7
              Re: "parent&qu ot; in a class __init__ def?

              akameswaran@gma il.com wrote:[color=blue]
              > bruno at modulix wrote:
              >[color=green]
              >>akameswaran@g mail.com wrote:
              >>[color=darkred]
              >>> Intuitively, the name lookup on
              >>>self.parent. foo would be faster than if you passed in the object in
              >>>question[/color]
              >>
              >>
              >>Each dot means doing a lookup in a namespace. The more dots, the more
              >>lookups. And lookups do have a cost.[/color]
              >
              > hmm, intuition may not be right in this case.[/color]
              [color=blue]
              > Lookups do have a cost - now I"m almost tempted to write and run a test
              > for this - but the cost of each lookup is also relative to the current
              > scope.[/color]

              A common "optimizati on" trick is to 'localize' references before a heavy
              loop, to avoid lookup cost, ie:

              def method(self, *args):
              dothis = self.dothis
              dothat = somemodule.some func
              CONST = othermodule.CON ST
              # heavy processing loop here

              [color=blue]
              > I haven't looked over the implementation of the python
              > interpreter - but I would hope the lookup on self would be optimized
              > and trivial.[/color]

              It's certainly not trivial. Must take into account instance attributes
              (in __dict__ or __slots__), class attributes, inherited attributes,
              overriding descriptors, non-overriding descriptors, __getattr__, etc...
              The incredible felxibility of Python's object model comes with a cost.
              [color=blue]
              > The next relevant question would be is it cheaper to
              > lookup self.parent or to look up a method variable,[/color]

              The second - cf above.
              [color=blue]
              > which I supsect
              > would depend on the number of names in self vs. number of names in the
              > method.[/color]

              Namespaces are mostly built upon hashtables, so the number of names
              should be mostly irrelevant.


              --
              bruno desthuilliers
              python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
              p in 'onurb@xiludom. gro'.split('@')])"

              Comment

              Working...