I can't run the method, without providing the argument for "self", in a class

Question:

Usually, one is able to run a method without providing an argument for the parameter "self", however, I’m unable to do that.

class Dice:
    def roll(self):
        x = (range(1, 7))
        y = (range(1, 7))
        from random import choice
        x1 = choice(x)
        y2 = choice(y)
        output = (x1, y2)
        return output


dice = Dice
dice.roll() # here it shows that parameter self is required

The Error shown is:
dice.roll() # here it shows that parameter self is
^^^^^^^^^^^
TypeError: Dice.roll() missing 1 required positional argument: ‘self’

Answers:

You need to initialize the class first.

dice = Dice()
dice.roll()

would work.

Or you could add the staticmethod decorator to your function

class Dice:
    @staticmethod
    def roll():
        x = (range(1, 7))
        y = (range(1, 7))
        from random import choice
        x1 = choice(x)
        y2 = choice(y)
        output = (x1, y2)
        return output
Answered By: Timbow Six
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.