473,503 Members | 1,656 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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,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
3 1759
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
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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
12540
by: Eric | last post by:
How can I dynamically assign an event to an element? I have tried : (myelement is a text input) document.getElementById('myelement').onKeyUp = "myfnc(param1,param2,param3)"; ...
8
5451
by: baustin75 | last post by:
Posted: Mon Oct 03, 2005 1:41 pm Post subject: cannot mail() in ie only when debugging in php designer 2005 -------------------------------------------------------------------------------- ...
23
3232
by: Jason | last post by:
Hi, I was wondering if any could point me to an example or give me ideas on how to dynamically create a form based on a database table? So, I would have a table designed to tell my application...
13
3684
by: Chua Wen Ching | last post by:
Hi there, I saw this article here in vb.net. http://www.error-bank.com/microsoft.public.dotnet.languages.vb.1/148992_Thread.aspx and ...
4
4232
by: Andres | last post by:
Hi all, I have the problem to assign a variable of type object to a specific class at runtime. I want to use a string variable that specify the class a want to set this object. Is something...
2
5025
by: John Regan | last post by:
Hello All I am trying to find the owner of a file or folder on our network (Windows 2000 Server) using VB.Net and/or API. so I can search for Folders that don't follow our company's specified...
3
2071
by: ricolee99 | last post by:
Hi everyone, I have a problem that i have been trying to solve for awhile. I'm given a code where the purpose is to create a general dataset mapper. Given any dataset, i have a class,...
0
2214
by: BigAl.NZ | last post by:
Hi Guys, I am trying to write/copy some code that uses events with a GPS. Everytime the GPS position updates the event fires. The GPS code is from a SDK Library that I got called GPS Tools...
0
7072
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7319
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
7449
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5570
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
4666
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3160
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
1498
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
730
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
373
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.