Help please: How to assign an object name at runtime

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • c0chong@gmail.com

    Help please: How to assign an object name at runtime

    Good day:
    Probably the answer to my question is staring me in the face, but the
    solution escapes me.

    The following is the input line of the file: SoftDict-.csv:
    ca1017,GRPHScri ptSet,ADD/REM,Adobe Acrobat 4.0=2005/06/14

    I expected an instance of Machine() to be created with a name ca1017.

    Instead, an object is assigned to l[0] named:
    <__main__.Machi ne instance at 0x01282558>

    -----------------------------
    Here is my code:

    class Machine:
    def __init__(self):
    self.software = []# Holds attributes of the instance
    def add(self, sware):
    self.software.a ppend(sware)# Append attribute
    return self.software
    def show(self):
    return self.software
    def __call__(self):
    return [ e for e in self.software]
    def cnt(self):
    return '%s' % (len(self.softw are))
    def installed(self, sware):
    if sware in self.software:
    return True
    else:
    return False

    class FileList:
    def __init__(self, filename):
    self.file = open(filename, 'r') # open and save file
    def __getitem__(sel f, i): # overload indexing
    line = self.file.readl ine()
    if line:
    return line # return the next line
    else:
    raise IndexError # end 'for' loops, 'in'
    def __getattr__(sel f, name):
    return getattr(self.fi le, name) # other attrs


    if __name__ == '__main__':

    import sys, fileinput, os, string # when run, not imported

    for line in FileList('SoftD ict-.csv'): # Treat .csv as a text
    if len(line)==1: break # Quit processing; end of file
    l=line.split(', ')# Split the line into constituent parts
    l[0]=Machine() # Create a Machine() object named: ca1017
    -------------------------------------------

    That's it. I evidently have no idea what I am doing.

    Thanks for your help.

  • Dan Sommers

    #2
    Re: Help please: How to assign an object name at runtime

    On 29 Jun 2005 17:55:44 -0700,
    "c0chong@gmail. com" <c0chong@gmail. com> wrote:
    [color=blue]
    > The following is the input line of the file: SoftDict-.csv:
    > ca1017,GRPHScri ptSet,ADD/REM,Adobe Acrobat 4.0=2005/06/14[/color]
    [color=blue]
    > I expected an instance of Machine() to be created with a name ca1017.[/color]
    [color=blue]
    > Instead, an object is assigned to l[0] named:
    > <__main__.Machi ne instance at 0x01282558>[/color]
    [color=blue]
    > -----------------------------
    > Here is my code:[/color]

    [ ... ]

    machines = {}
    [color=blue]
    > for line in FileList('SoftD ict-.csv'): # Treat .csv as a text
    > if len(line)==1: break # Quit processing; end of file
    > l=line.split(', ')# Split the line into constituent parts[/color]

    Delete this:
    [color=blue]
    > l[0]=Machine() # Create a Machine() object named: ca1017[/color]

    And add this in its place:

    machines[l[0]] = Machine()

    This will create a dictionary that maps the string 'ca1017' to a newly
    created Machine object.

    HTH,
    Dan

    --
    Dan Sommers
    <http://www.tombstoneze ro.net/dan/>

    Comment

    • John Machin

      #3
      Re: Help please: How to assign an object name at runtime

      c0chong@gmail.c om wrote:[color=blue]
      > Good day:
      > Probably the answer to my question is staring me in the face, but the
      > solution escapes me.
      >
      > The following is the input line of the file: SoftDict-.csv:
      > ca1017,GRPHScri ptSet,ADD/REM,Adobe Acrobat 4.0=2005/06/14
      >
      > I expected an instance of Machine() to be created with a name ca1017.[/color]

      There is absolutely no basis at all for this expectation. How did you
      arrive at it?
      [color=blue]
      >
      > Instead, an object is assigned to l[0] named:
      > <__main__.Machi ne instance at 0x01282558>[/color]

      The object is assigned to l[0] exactly as you dictated, i.e. its name is
      l[0]. The former referent of l[0] i.e. the string whose value is
      "ca1017" is no longer in view and will be garbage-collected.

      What are you really wanting to do?

      BTW, don't use "l".
      [color=blue]
      >
      > -----------------------------
      > Here is my code:
      >
      > class Machine:
      > def __init__(self):
      > self.software = []# Holds attributes of the instance[/color]

      Do you mean like self.software ultimately =
      ['GRPHScriptSet' , 'ADD/REM', 'Adobe Acrobat 4.0=2005/06/14'] ?

      That's not quite what the man meant when he said 'object-oriented'!!
      [color=blue]
      > def add(self, sware):
      > self.software.a ppend(sware)# Append attribute
      > return self.software
      > def show(self):
      > return self.software
      > def __call__(self):
      > return [ e for e in self.software][/color]

      Isn't that the same as "return self.software"?

      So obj.show() and obj() return an attribute of obj? That's an
      "interestin g" interface.

      Lose the __call__ -- you don't need it.

      [color=blue]
      > def cnt(self):
      > return '%s' % (len(self.softw are))[/color]

      Why not just return the length as an integer???
      [color=blue]
      > def installed(self, sware):
      > if sware in self.software:
      > return True
      > else:
      > return False[/color]

      Try "return sware in self.software"
      [color=blue]
      >
      > class FileList:
      > def __init__(self, filename):
      > self.file = open(filename, 'r') # open and save file
      > def __getitem__(sel f, i): # overload indexing
      > line = self.file.readl ine()
      > if line:
      > return line # return the next line
      > else:
      > raise IndexError # end 'for' loops, 'in'
      > def __getattr__(sel f, name):
      > return getattr(self.fi le, name) # other attrs
      >
      >
      > if __name__ == '__main__':
      >
      > import sys, fileinput, os, string # when run, not imported
      >
      > for line in FileList('SoftD ict-.csv'): # Treat .csv as a text
      > if len(line)==1: break # Quit processing; end of file
      > l=line.split(', ')# Split the line into constituent parts
      > l[0]=Machine() # Create a Machine() object named: ca1017
      > -------------------------------------------
      >
      > That's it. I evidently have no idea what I am doing.[/color]

      The whole FileList class is pointless. Step 1: replace """for line in
      FileList(filena me):"""

      with """for line in open(filename): """

      and lose the """if .... : break""" line.

      Step 2: read up on the csv module, and lose the "split".

      Step 3: you are unlikely to *ever* need the string and fileinput modules

      Step 4: you import 4 modules you don't use. Why?

      Oh and BTW Step 0: what are the requirements for this exercise, what do
      the fields in the file actually represent, what is that bloody = sign
      between 'Adobe Acrobat' and the date aaaarrrggghhhh words fail me [finally]


      .... exiting in pursuit of paracetamol,
      John

      Comment

      • Steven D'Aprano

        #4
        Re: Help please: How to assign an object name at runtime

        John Machin wrote:
        [color=blue]
        > BTW, don't use "l".[/color]

        Excellent advice.

        But since the original poster appears to be rather a
        newbie, perhaps a little bit of explanation would be
        useful.

        Variables like l and I should be avoided like the
        plague, because in many fonts and typefaces they are
        indistinguishab le, or look like the digit 1. Yes, I'm
        sure you are using a fancy syntax-highlighting editor
        that colours them differently, but the day will come
        that you are reading the code on pieces of dead tree
        and then you'll be sorry that you can't tell the
        difference between l and 1.

        Another bit of advice: never use words like "list",
        "str", "int" etc as names for variables, because they
        conflict with Python functions:

        py> list("AB")
        ['A', 'B']
        py> list = []
        py> list("AB")
        Traceback (most recent call last):
        File "<stdin>", line 1, in ?
        TypeError: object of type 'list' is not callable

        In general, I only use single letter variable names
        like a, b, L (for a list), s (for a string) in short
        function code, where the nature of the variable is
        obvious from the context:

        def stepsum(n, step=1):
        total = 0
        for i in range(0, n, step):
        total + i
        return total

        def add_colon_str(s , t):
        return s + ": " + t

        It doesn't need much explanation to understand what s
        and t are. But for anything more complex, I always use
        descriptive names.


        --
        Steven.

        Comment

        Working...