![](/img/trans.png)
[英]How do I use the python-decorator package to decorate classmethods?
[英]How do I use classmethods on defs that work without classmethods but don't work when added
我想向其中添加类方法的代码,但不知道如何使它起作用。 该代码按原样运行正常,但是需要注释中所述的类方法
# 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()
我同意这样的意见,即不应将这些方法用作类方法。
但是,如果必须,您将无法在其中使用self
。 自我是指对象,但是类方法不会在对象上调用,它们是为类调用的。 因此,您将无法再将value
存储在对象中,因为您没有任何值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.