user3186749
user3186749

Reputation: 17

Using a class of variables for function argument

I am new to python, about 3 days, and I am not sure if I have worded the question properly.

I have a class:

class blue_slime:
    nom = "BLUE SLIME"
    img = "  /\ \n( o o)"
    str = 10
    int = 5
    dex = 5
    con = 10
    spd = 10
    hp = ((con + str) / 2)
    mp_bonus = 1

and I want to use the variables from this class in another function.

def encounter(nom, hp, img):
    print(char_name + " encountered a " + nom + "!!!")
    wait()
    while hp > 0:
        battle(hp, img)
    else:
        stats()

now I know that I could call this by using

encounter(blue_slime.nom, blue_slime.hp, blue_slime.img)

but I would much rather (and think it may be necessary for my program down the line) be able to just use the class name as the function argument and then in the function I can just utilize all variables without having to write them in each time. While this may sound like laziness, I am thinking about making the encounter be random, so 10% chance to encounter(blue_slime) 10% chance to encounter(green_slime).

I feel the easiest way to implement this would be to somehow condense all the variables in "class blue_slime" into one name.

please let me know if there is a way to do this, perhaps I have just not learned it yet.

Upvotes: 0

Views: 38

Answers (1)

Stephen C
Stephen C

Reputation: 2036

You can just pass the class into the function is that's what you wanna do. That will solve your problem:

def encounter(monster):
    monster.hp
    monster.img
    # etc.

Here's some tips:

As was already mentioned in the comments on your question, you probably want to be using instances of those classes instead of the actual classes. I'll give a sample class with a few pointers:

class BlueSlime: # Using CapCase like this is normal for class names
    # You can use this space to make class variables.
    # These will be the same across all the classes.
    # Probably use this for initializing your instances
    base_hp = 5
    base_int = 10
    base_dmg = 3

    def __init__(self): # The "Constructor" of your instances
        self.current_hp = self.base_hp # self refers to the instances
        self.int = self.base_int
        self.dmg = self.base_dmg

The instance thing is nice because if some of your slimes take dmg, you don't necessarily want them all to take dmg.

bs1 = BlueSlime() # Init the instance
bs2 = BlueSlime()

# bs1 takes 1 dmg (May want a method to do this)
bs1.hp -= 1

bs1.hp
# Now 4

bs2.hp
# Still 5

Getting back to your question, at this point, you can pass these instances into your encounter function.

def encounter(monster):
    # Something happens here to reduce the hp, it will reduce the instance's hp

    # Something happens here to deal dmg, you can look it up on the instance
    player.hp -= monster.dmg # Something like this....
    # etc

Upvotes: 1

Related Questions