如果不提供“self”的参数,我无法在类中运行该方法[重复]

问题描述 投票:0回答:1

通常,可以在不为参数“self”提供参数的情况下运行一个方法,但是,我做不到。

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

显示的错误是: dice.roll() # 这里表明参数 self 是 ^^^^^^^^^^^^ 类型错误:Dice.roll() 缺少 1 个必需的位置参数:'self'

python python-3.x class
1个回答
0
投票

需要先初始化类

dice = Dice()
dice.roll()

会工作。

或者您可以将静态方法装饰器添加到您的函数中

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
© www.soinside.com 2019 - 2024. All rights reserved.