Mattattack
Mattattack

Reputation: 189

using a variable from a class in python

I think this question has been asked before but I have not found an answer suited to my problem. I basically have a class for different characters, which each have a cost. When creating a character, I want to take their cost away from the players score.

Here is an example of a class:

class Assassin(pygame.sprite.Sprite):
    def __init__(self, x, y, row, column):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load("assassin.png")
        self.x = x
        self.type = "assassin"
        self.y = y
        self.rect = self.image.get_rect(center=(self.x, self.y))
        self.damage = 60
        self.health = 40
        self.speed = 2
        self.move = False
        self.cost = 4
        self.row = row
        self.column = column

And here is the code where I would want to use the variable:

 if assassin.collidepoint(pygame.mouse.get_pos()) and mouseDown[0]:
            for block in blockGroup:
                if block.team1Taken == False and block.column ==1:
                    team1.add(Assassin(block.team1[0], block.team1[1], block.row, block.column))
                    block.team1Taken = True
                    score -= Assassin.__init__.cost #Example of what I think you would do
                    break

I hope I have explained this well enough to understand what I want.

Upvotes: 0

Views: 85

Answers (2)

chgsilva
chgsilva

Reputation: 768

You can't call score -= Assassin.__init__.cost in python. The init method is the constructor of the Class and should be used to do so.

The value that you want is inside the object that you created, so you could call assassin.cost directly, assuming that assassin is the object.

So, you just need to change to:

if assassin.collidepoint(pygame.mouse.get_pos()) and mouseDown[0]:
            for block in blockGroup:
                if block.team1Taken == False and block.column ==1:
                    current_assassin = Assassin(block.team1[0], block.team1[1], block.row, block.column)
                    team1.add(current_assassin)
                    block.team1Taken = True
                    score -= current_assassin.cost
                    break

Upvotes: 2

DeepSpace
DeepSpace

Reputation: 81594

You will need to keep a reference to the Assassin instance you create and then access its cost attribute:

if assassin.collidepoint(pygame.mouse.get_pos()) and mouseDown[0]:
    for block in blockGroup:
        if block.team1Taken == False and block.column == 1:
                new_assassin = Assassin(block.team1[0], block.team1[1],
                                        block.row, block.column)
                team1.add(new_assassin)
                block.team1Taken = True
                score -= new_assassin.cost
                break

Upvotes: 2

Related Questions