There is this code that I would like to add classmethods to but don't know how to get it to work. The code runs fine as is but needs classmethods as stated by the comments
# 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()
I agree with the comment that these methods SHOULD NOT be made classmethods.
But if you must, you cannot use self
there. Self refers to an object, but classmethods are not called on an object, they're called for a class. So you can no longer store the value
in the object, because you have none.