CoopTang
CoopTang

Reputation: 129

Using an __init__ argument in other functions of the same class

So I'm trying to design a class for a weapon system in a text based game. Basically, I want all swords to deal 1-6 damage and then add damage based on the weapons modifier. I got the class to work if I call the function in the class with the modifier, but I want to set the class once and not have to type it multiple times

This is the code I have.

import dice #uses random generation to simulate dice rolls

class sword():

    def __init__(self, name, modifier):
        self.name = name
        self.mod = modifier

    def dmg(self, modifier):
        base = dice.d6

        self.dmg = base + modifier
        return self.dmg

x = sword("Sword of coolness", 1)
print x.name
print x.dmg(1)

Upvotes: 0

Views: 55

Answers (1)

BrenBarn
BrenBarn

Reputation: 251373

That's why you did self.mod = modifier. Now the value is available to methods as self.mod. So you can make your method:

def dmg(self):
    base = dice.d6

    self.dmg = base + self.mod
    return self.dmg

As YS-L notes, in a comment, though, you probably don't want to do that, since you're overwriting the dmg method with a value. Maybe a better idea to give the method a different name:

def modify_dmg(self):
    base = dice.d6

    self.dmg = base + self.mod
    return self.dmg

Upvotes: 2

Related Questions