Nikhil Menghrajani
Nikhil Menghrajani

Reputation: 133

attribute error in python (code-skulpor)

im trying to run the following code on codeskulptor. and its giving an error: Line 17: AttributeError: 'card' object has no attribute 'rank'. y is this so?

import simplegui

ranks=('A','2','3','4','5','6','7','8','9','T','J','Q','K')
suits=('C','S','H','D')

card_centre=(36.5,49)
card_size=(73,98)
tiled_image=simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/cards.jfitz.png")

class card:
    def _init_(self,suit,rank):
        self.rank=rank
        self.suit=suit

    def draw(self,canvas,loc):
        global ranks,suits
        i=ranks.index(self.rank)
        j=suits.index(self.suit)
        card_pos=[card_centre[0]+i*card_size[0],card_centre[1]+j*card_size[1]]
        canvas.draw_image(tiled_image,card_pos,card_size,loc,card_size)

def draw(canvas):
    one_card.draw(canvas,[300,200])

frame=simplegui.create_frame("Card draw",600,400)
frame.set_draw_handler(draw)
one_card=card('H','J')
frame.start()

Upvotes: 0

Views: 47

Answers (1)

tobias_k
tobias_k

Reputation: 82889

Not sure whether this really is the problem, but your _init_ method should look like this:

def __init__(self, suit, rank):
    self.rank = rank
    self.suit = suit

Note that it has two __ instead of just one _. This will make it a constructor (instead of just some method that happens to be called _init_), and only then it will actually be called when you create your card instance with one_card = card('H','J') and only then the attributes self.rank and self.suit will get initialized.

However, if this is the problem, you should actually get another error even before that, namely TypeError: this constructor takes no arguments because there is no constructor defined that takes two parameters, but maybe your IDE can statically (before actually running the program) recognize the one problem but not the other.

Upvotes: 1

Related Questions