【发布时间】:2020-05-26 15:20:02
【问题描述】:
我想在 str 中运行 di 但它显示 NameError: name 'di' is not defined when I run it.
class DicePile:
def __init__(self, initQuantity, initSides,initrollCount = 0, initrolled = False): # constructor
self.setQuantity(initQuantity)
self.setSides(initSides)
self.__rollcount = initrollCount
self.rolled = initrolled
def __str__(self): # generate a string representation of the object
rc = '(roll count:' + str(self.__rollcount) + ')'
if self.rolled:
resultString = str(self.__results)
else:
resultString = 'not rolled'
return di(self) + ': ' + resultString + rc
def di(self):
return str(self.__quantity) + 'd' + str(self.__sides)
我还在学习 OOP 和函数,这个问题困扰了我好几个小时
【问题讨论】:
-
这不是你调用方法的方式。使用
self.di()而不是di(self) -
DicePile.di(self)会起作用,但不建议这样做,因为它既单一又绕过继承。 -
什么是
setQuatity和setSides?我怀疑它们是微不足道的设置器,可以丢弃以支持直接分配给属性。