LinuxQuestions.org
Help answer threads with 0 replies.
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices

Reply
 
LinkBack Search this Thread
Old 08-20-2008, 07:34 PM   #1
Valkyrie_of_valhalla
Member
 
Registered: Jan 2006
Location: Romania
Distribution: Suse 12.0, Slackware 12.1, Debian, Ubuntu, Gentoo
Posts: 301

Rep: Reputation: 30
python: list of class-objects?


In brief:

I'm trying to create a list of class objects, but if I for example run something like this:

Code:
alist=[None]*7
for i in range(7)
    alist[i]=aClass()
The list will still be formed of just None-type objects in the end.

If I try to do that without the alist=[None]*7, I get an index out of range error.

So, how is this done exactly? Is it even possible? Or is there another way to do it?


In depth:

The final goal is to create a magic the gathering-like open source clone.

The part of the code that doesn't work looks something like this:

Code:
class Deck():
    
    def __init__(self,deckfilename):
        f=open('./data/'+deckfilename,'r')
        self.n=int(f.readline())
        self.cards=[None]*100
        self.nr=0
        for i in range(self.n):
            tempcard=Card(strip(f.readline()),strip(f.readline()))
            tempcard.nc=int(f.readline())
            tempcard.type=int(f.readline())
            tempcard.mana=int(f.readline())
            tempcard.atk=int(f.readline())
            tempcard.hp=int(f.readline())
            tempcard.a1=strip(f.readline())
            tempcard.a2=strip(f.readline())
            tempcard.a3=strip(f.readline())
            self.nr=self.nr+1
            for j in range(tempcard.nc-1):
                self.cards[self.nr]=tempcard
                self.nr=self.nr+1
        for i in range(9):
            if self.cards[i]==None :
                print 'smth is wrong'
And guess what? It prints 'smth is wrong' 9 times... (yes there are 3 cards in the txt file, each should be inserted 3 times in the deck, and it seems to read correctly from the file).

And if I try to do something like print self.cards[1].nc it says the "None" class has no nc attribute.

The card class is also sort of strange. It looks like this:

Code:
class Card():
    
    def __init__(self, filename,tbfilename):
        """
        Reads from file all the abilities of the card.    
        Saves them in class variables.    
        """    
        self.filename=filename
        self.tbfilename=tbfilename
        self.img = None
        self.tb=None
        
        self.nc=0
        
        self.type=0
        self.mana=0
        self.atk=0
        self.hp=0
        
        self.tatk=0
        self.thp=0
        
        self.a1=''
        self.a2=''
        self.a3=''
        self.load_image()
        
    def load_image(self):
        """
        Loads the image of the card
        """
        print "Loading image "+self.filename
        self.img=image.load("./data/"+self.filename)
        self.tb = image.load("./data/"+self.tbfilename)
        print self.img
            
    def draw_card(self,x,y):
        """
        Draws the card at given x,y coordinates
        """        
        self.tb.blit(x,y)
Any ideas what I could do to make it work? Or another solution how I could do this?

Thanks for your time. Any suggestion is welcomed.
 
Old 08-20-2008, 10:00 PM   #2
ntubski
Senior Member
 
Registered: Nov 2005
Distribution: Debian
Posts: 2,307

Rep: Reputation: 767Reputation: 767Reputation: 767Reputation: 767Reputation: 767Reputation: 767Reputation: 767
Quote:
Originally Posted by Valkyrie_of_valhalla View Post
In brief:

I'm trying to create a list of class objects, but if I for example run something like this:

Code:
alist=[None]*7
for i in range(7)
    alist[i]=aClass()
The list will still be formed of just None-type objects in the end.
This works for me:

Code:
>>> alist=[None]*7    
>>> alist
[None, None, None, None, None, None, None]
>>> for i in range(7):   
...     alist[i]=aClass()
...      
>>> alist                                                                                
[<__main__.aClass instance at 0xa1580>, <__main__.aClass instance at 0x11f918>, <__main__.aClass instance at 0x11f940>, <__main__.aClass instance at 0x11f968>, <__main__.aClass inst\
ance at 0x11f990>, <__main__.aClass instance at 0x11f9b8>, <__main__.aClass instance at 0x11f9e0>]

Although I would suggest simply appending to the list, instead of messing around with indices:

Code:
>>> alist=[]
>>> for i in range(7):
...     alist.append(aClass())
... 
>>> alist
[<__main__.aClass instance at 0x11f850>, <__main__.aClass instance at 0x11f198>, <__main__.aClass instance at 0x11f170>, <__main__.aClass instance at 0x11f8a0>, <__main__.aClass ins\
tance at 0x11f800>, <__main__.aClass instance at 0x11f8c8>, <__main__.aClass instance at 0x11f8f0>]
(okay doesn't really help much for the toy example, but your actual code has a bunch of book-keeping with the indices and lengths as if you were writing C...)

Also x = x + 1 can be replaced by x += 1
 
Old 08-21-2008, 08:04 AM   #3
Valkyrie_of_valhalla
Member
 
Registered: Jan 2006
Location: Romania
Distribution: Suse 12.0, Slackware 12.1, Debian, Ubuntu, Gentoo
Posts: 301

Original Poster
Rep: Reputation: 30
Ahh works perfectly with the append function

Many many thanks!

It's true I've coded mostly in C and Pascal so far, and I'm trying to learn the Python sytnax on the fly as I code. That's probably why it looks so much C-ish.
 
Old 08-24-2008, 06:26 AM   #4
jcookeman
Member
 
Registered: Jul 2003
Location: London, UK
Distribution: FreeBSD, OpenSuse, Ubuntu, RHEL
Posts: 417

Rep: Reputation: 33
use list comprehensions

While append works in this situation, list comprehensions are far more efficient:

Code:
>>> class foo:
...     pass
...
>>> test = [foo() for i in range(7)]
>>> test
[<__main__.foo instance at 0x2841756c>, <__main__.foo instance at 0x2841760c>, <__main__.foo instance at 0x284174ec>, <__main__.foo instance at 0x2841750c>, <__main__.foo instance at 0x2841764c>, <__main__.foo instance at 0x2841766c>, <__main__.foo instance at 0x284176ac>]
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

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

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are Off
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
wxPython: is there a list of all the EVT_* objects? BrianK Programming 2 07-24-2008 08:59 PM
copy constructor for class containing array of vaiable size objects ? qwijibow Programming 4 12-21-2005 09:50 PM
Implementing a vector class from a list class purefan Programming 9 04-14-2005 10:48 PM
Class Arrays in Python rootyard Programming 1 02-13-2004 10:58 PM
arrays of pointers to class objects tdurden Programming 5 12-16-2002 10:47 AM


All times are GMT -5. The time now is 01:54 AM.

Main Menu
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
identi.ca: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration