如何在没有classmethods但在添加时不起作用的defs上使用classmethods

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

有这个代码,我想添加类方法但不知道如何让它工作。代码运行正常,但需要注释所述的类方法

# class definition for an n-sided die

# import packages

import random

class MSdie(object): 
  #constructor here

    def __init__( self ):
        self.sides = 6
        self.roll()

#define classmethod 'roll' to roll the MSdie

    def roll( self ):

        self.value = 1 + random.randrange(self.sides)

        return self.value

#define classmethod 'getValue' to return the current value of the MSdie

    def getValue(  self ):

        return self.value

#define classmethod 'setValue' to set the die to a particular value
    #def setValue(self):

def roller():
    r1 = MSdie()

    for n in range (4):
        print(r1.roll())

roller()
python class-method dice
1个回答
0
投票

我同意这些方法不应该成为类方法的评论。

但如果你必须,你不能在那里使用self。 Self指的是一个对象,但是类方法不是在一个对象上调用的,它们被称为一个类。所以你不能再将value存储在对象中,因为你没有。

© www.soinside.com 2019 - 2024. All rights reserved.