Methods

A method is a function within a class. You can define any number of functions within a class in the same way that you would a regular function. The only difference is the extra parameter in the definition that refers to the instance of the class, in these examples I’ll call that variable self.

Up until now we have just used our classes to store multiple variables in a single object. This has been a good way to keep related information in a single variable that we can pass around. Methods allow us to add functionality to classes. These functions should only be concerned with the class and not something common that might be useful for other parts of our code.

Let’s add a method to our class.

from random import randint

class Weapon(object):
    def __init__(self, name, damage_type, damage, speed):
        self.name = name
        self.damage_type = damage_type
        self.damage = damage
        self.speed = speed

    def random_damage(self):
        return randint(1,self.damage)

short_sword = Weapon("Short Sword", "Piercing", 5, 10)
battle_axe = Weapon("Battle Axe", "Slashing", 20, 3)

print(short_sword.name,"does",short_sword.damage,"damage")

class MagicWeapon(Weapon):
    def __init__(self, name, damage_type, damage, speed, effect):
        super().__init__(name, damage_type, damage, speed)
        self.effect = effect

magic_spear = MagicWeapon("Magic Spear", "Piercing", 25, 7, "Fire")
print(magic_spear.name, "has a magical", magic_spear.effect, "effect")

for x in range(10):
    damage = magic_spear.random_damage()
    print(damage)

This could give an output of:

Short Sword does 5 damage
Magic Spear has a magical
Fire effect
14
4
9
8
21
8
14
17
18
6

You can see that we call the method in the same way we access a variable, using a . after the variable name:

damage = magic_spear.random_damage()

magic_spear is the name of the variable in which we are storing the class object, then a . then the name of the method random_damage(). Remember you are calling a function so you need the brackets even if there are no parameters to pass in.

Next: Importing modules and packages

Report a Glow concern
Cookie policy  Privacy policy

Glow Blogs uses cookies to enhance your experience on our service. By using this service or closing this message you consent to our use of those cookies. Please read our Cookie Policy.