By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,676 Members | 2,236 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,676 IT Pros & Developers. It's quick & easy.

Help please: How to assign an object name at runtime

P: n/a
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,GRPHScriptSet,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__.Machine 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.append(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.software))
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__(self, i): # overload indexing
line = self.file.readline()
if line:
return line # return the next line
else:
raise IndexError # end 'for' loops, 'in'
def __getattr__(self, name):
return getattr(self.file, name) # other attrs
if __name__ == '__main__':

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

for line in FileList('SoftDict-.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.

Jul 19 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a
On 29 Jun 2005 17:55:44 -0700,
"c0*****@gmail.com" <c0*****@gmail.com> wrote:
The following is the input line of the file: SoftDict-.csv:
ca1017,GRPHScriptSet,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__.Machine instance at 0x01282558> -----------------------------
Here is my code:
[ ... ]

machines = {}
for line in FileList('SoftDict-.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
Delete this:
l[0]=Machine() # Create a Machine() object named: ca1017


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.tombstonezero.net/dan/>
Jul 19 '05 #2

P: n/a
c0*****@gmail.com wrote:
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,GRPHScriptSet,ADD/REM,Adobe Acrobat 4.0=2005/06/14

I expected an instance of Machine() to be created with a name ca1017.
There is absolutely no basis at all for this expectation. How did you
arrive at it?

Instead, an object is assigned to l[0] named:
<__main__.Machine instance at 0x01282558>
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".

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

class Machine:
def __init__(self):
self.software = []# Holds attributes of the instance
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'!!
def add(self, sware):
self.software.append(sware)# Append attribute
return self.software
def show(self):
return self.software
def __call__(self):
return [ e for e in self.software]
Isn't that the same as "return self.software"?

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

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

def cnt(self):
return '%s' % (len(self.software))
Why not just return the length as an integer???
def installed(self, sware):
if sware in self.software:
return True
else:
return False
Try "return sware in self.software"

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

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

for line in FileList('SoftDict-.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.


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

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
Jul 19 '05 #3

P: n/a
John Machin wrote:
BTW, don't use "l".


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
indistinguishable, 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.

Jul 19 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.