473,569 Members | 2,752 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,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.

Jul 19 '05 #1
3 1765
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,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:
[ ... ]

machines = {}
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
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.tombstoneze ro.net/dan/>
Jul 19 '05 #2
c0*****@gmail.c om 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,GRPHScri ptSet,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__.Machi ne 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.a ppend(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
"interestin g" interface.

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

def cnt(self):
return '%s' % (len(self.softw are))
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__(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.


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

Jul 19 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
12552
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)"; document.getElementById('myelement') = new Function("myfnc(param1,param2,param3)");
8
5459
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 -------------------------------------------------------------------------------- Hello, I have a very simple problem but cannot seem to figure it out. I have a very simple php script that sends a test email to myself. When I...
23
3245
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 to create certain textboxes, labels, and combo boxes? Any ideas would be appreciated. Thanks
13
3687
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 http://www.opennetcf.org/forums/post.asp?method=ReplyQuote&REPLY_ID=3922&TOPIC_ID=2224&FORUM_ID=35
4
4237
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 similar to add a new control to a form using the controls collection: Private Sub CommandCreateInstance_Click()
2
5031
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 folder structure and naming conventions and then send a Net send message to those users telling them to rectify. The information I want to get is when...
3
2080
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, "Mapper.cs" that's supposed to map objects from any type of dataset to any type of object. Inside Mapper.cs, there's a method, object Map(Type...
0
2221
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 from www.franson.com For some reason my code below doesnt work - the GpsFixEvent never seems to "fire" as it were.
0
7609
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7921
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8118
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7666
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6278
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5504
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3636
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1208
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
936
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 can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.