Python Programming
 
Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
User Name:
Password:
Remember me

The Shed is going Social! Join us on FaceBook and Twitter and chime in on the conversation.

Go Back   Dev Shed ForumsProgramming LanguagesPython Programming

Reply
Add This Thread To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Thread Tools Search this Thread Rate Thread Display Modes
 
Unread Dev Shed Forums Sponsor:
  #1  
Old February 12th, 2013, 03:11 PM
JohnPetrucci00 JohnPetrucci00 is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Dec 2012
Posts: 14 JohnPetrucci00 User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 4 h 45 m 30 sec
Reputation Power: 0
Loop to Efficiently Populate Class Attributes

Hello,

I am starting to get into classes in Python and have the following case:

I am reading a CSV file with 61 columns (each column with a unique header label). I created a class with 61 attributes (I apologize if I'm using the terms incorrectly). A portion of the class is below:

Code:
class partProperties:
    def setPartID(self, number):
        self.partID = number
    def setPartName(self, text):
        self.partName = text



Only 2 of the 61 functions are shown. I would like to read each row of the CSV and 'automatically' set the attributes for a new instance of this class (each row will be an instance). The list of attributes in the class is in the same order as the columns in the CSV.

My question: is there a way to set all of the attributes without typing each unique call (i.e. 'setPartID')? Ideally I would like to index each attribute so I can loop through all of them as I read each row of the CSV. Is this possible? How would an experienced programmer approach this?

Thanks.

-John

Reply With Quote
  #2  
Old February 12th, 2013, 07:08 PM
b49P23TIvg's Avatar
b49P23TIvg b49P23TIvg is offline
Contributing User
Dev Shed Loyal (3000 - 3499 posts)
 
Join Date: Aug 2011
Posts: 3,353 b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level) 
Time spent in forums: 1 Month 2 Weeks 3 Days 8 h 3 m 36 sec
Reputation Power: 383
This answer is ridiculous.

The attributes of the class are data driven. Why are the generic objects better than dictionaries? I can't think of a reason. One could insert a price method that depends on item featues, and that would be a good reason to use a custom class instead of a dictionary. The class is restrictive, the keys need to be valid python identifiers.
Code:
import io
import sys
import csv
import pprint

class generic(dict):
    pass

def generic_factory(file_object):
    reader = iter(csv.reader(file_object))
    attributes = next(reader)
    result = []
    try:
        while True:
            row = next(reader)
            kwargs = dict(zip(attributes,row))
            result.append(generic(**kwargs))
    except StopIteration:
        pass
    return result

DATA = '"partID","partName"\n35553,"snare"\n28709,"rim"\n85332,"skin"'

if sys.version[0] == '2':
    DATA = DATA.decode('utf8')

FAKEFILE = io.StringIO(DATA)

FAKEFILE.seek(0)

OBJECTS = generic_factory(FAKEFILE)

FAKEFILE.close()

pprint.pprint([str(O) for O in OBJECTS])


It occurs to me this is easier:
Code:
import io
import sys
import csv
import pprint

DATA = '"partID","partName"\n35553,"snare"\n28709,"rim"\n85332,"skin"'

if sys.version[0] == '2':
    DATA = DATA.decode('utf8')

with io.StringIO(DATA) as FAKEFILE:
    FAKEFILE.seek(0)
    OBJECTS = [O for O in csv.DictReader(FAKEFILE)]

pprint.pprint([str(O) for O in OBJECTS])
__________________
[code]Code tags[/code] are essential for python code!

Last edited by b49P23TIvg : February 12th, 2013 at 07:10 PM.

Reply With Quote
  #3  
Old February 13th, 2013, 09:42 AM
JohnPetrucci00 JohnPetrucci00 is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Dec 2012
Posts: 14 JohnPetrucci00 User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 4 h 45 m 30 sec
Reputation Power: 0
Thank you very much for the response. I am impressed how concise the code is to read the CSV into a dictionary. I need to spend some time studying your code to understand it.

The challenge I'm facing is that each CSV file that is read may contain only a subset of the 61 columns in the 'master' header.

If I decide to go the class route, is there a way of defining new instances on the fly from a dynamic variable name?

For example, as each row is read, the instances are created and named:

'part-1'
'part-2'
'part-3'

From what I've seen, it appears I may need to use eval for this?

-John

Reply With Quote
  #4  
Old February 13th, 2013, 10:30 AM
JohnPetrucci00 JohnPetrucci00 is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Dec 2012
Posts: 14 JohnPetrucci00 User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 4 h 45 m 30 sec
Reputation Power: 0
After experimenting, it seems that the following code accomplishes instantiation from dynamic variable names:

Code:
partObjectNames.insert(i, 'line-' + str(i) + '-part')	# Create the name of the object to hold the extracted inputs
partObjectNames[i] = partProperties(extractedInputs)	# Instantiate the object

Reply With Quote
Reply

Viewing: Dev Shed ForumsProgramming LanguagesPython Programming > Loop to Efficiently Populate Class Attributes

Developer Shed Advertisers and Affiliates



Thread Tools  Search this Thread 
Search this Thread:

Advanced Search
Display Modes  Rate This Thread 
Rate This Thread:


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
View Your Warnings | New Posts | Latest News | Latest Threads | Shoutbox
Forum Jump

Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
  
 


Powered by: vBulletin Version 3.0.5
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.

© 2003-2013 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap