属性和setter装饰器未在子类中运行



我希望有人能帮忙。我正在使用《Python(第二版(:一天内学会Python并学好》一书。

我已经完成了这个项目,只是发现了最后的错误,但有一个让我完全不知所措。

正在编码的游戏向用户提供两个游戏的选项。然后,它为他们想要回答的问题数量提供了一个选项。每个游戏都是game类的一个子类。在Game类中,有getter和setter的decorator,但它们不会被调用。。。曾经它甚至不会打印我添加到调试中的行。我的理解是,如果这些是在基类中定义的,那么它们将由子类初始化,除非被重写。

我已经根据书中的答案检查了我的代码,还检查了语法,一切看起来都很好。我也没有发现任何其他有帮助的问题。

此外,我正在使用Pythonista来完成这一切。不确定这是否是一个错误?

下面是类代码,不确定在这个阶段实际的程序是否有帮助,但如果需要,我可以发布

感谢您提前提供的帮助!


class Game:
def __init__ (self, noOfQuestions = 0):
self._noOfQuestions = noOfQuestions # the underscored argument has property definitions
@property # returns one as the other when queried
def noOfQuestions(self):
print('getter')
return self._noOfQuestions
@noOfQuestions.setter # to set the value it needs to meet the parameters below
def noOfQuestions(self, value):
print('1st line')
if value < 1:
print('2nd line')
self._noOfQuestions = 1
print('The minimum number of questions is one, so there will be one.')
elif (value > 10):
print('3rd line')
self._noOfQuestions = 10
print('The maximum number of questions is ten, so there will be ten.')
else :
print('4th line')
self._noOfQuestions = value
class BinaryGame(Game): # a sub class of Game
def generateQuestions(self): #this will generate binary numbers, get the user response and compare
from random import randint
score = 0 # initialise score to zero
for q in range(self.noOfQuestions): # for the number of questions
base10 = randint(1, 100) # generate a random int between 1 and 100
userResult = input('nPlease enter the binary version of %d' %(base10)) # user to enter binary version
while True: # until broken
try:    # try to cast the int as binary
answer = int(userResult, base = 2) 
if answer == base10: # compare the user answer to the correct answer
print('nThat is correct, well done!')
score += 1 # add 1 to the score
break
else:
print('nThat is incorrect, are you an idiot? The correct answer is {:b}.' .format(base10))
break
except : # if they didn't type in a binary number
print('nAnswer must be base-2 (binary), please try again.')
userResult = input('nPlease enter the binary version of %d' %(base10))
return score

class MathGame(Game): #sub class of Game
def generateQuestions(self): 
from random import randint # import randint
score = 0 # set the score to zero
numberList = [0, 0, 0, 0, 0] #initiate number list
symbolList = ['', '', '', ''] # initiate symbol list
operatorDict = {1 : "+", 2 : "-", 3 : "*", 4 : "**"} # dictionary of opperators
for q in range(self.noOfQuestions): #for the number of questions
for i in range(0,5): #generate random numbers into the number list
numberList[i] = randint(1,9)
for i in range(0, 4): # generate random symbols into symbol list avoiding adjacent **
if i > 0 and symbolList[i-1] == "**": 
symbolList[i] = operatorDict[randint(1, 3)]
else:
symbolList[i] = operatorDict[randint(1, 4)]
questionString = str(numberList[0]) # add the final number to the string
for i in range(0, 4): # for each item in the symbol list add a number and symbol
questionString = questionString + symbolList[i] + str(numberList[i+1])
result = eval(questionString) # caluclate the correct answer
questionString = questionString.replace("**", "^") # swap ** for ^
userResult = input('Solve %s' %(questionString))
while True: # get an answer, check it's an int and then check if it's correct
try:            
answer = int(userResult)
if answer == result:
print("nWell done, that's correct")
score =+1
break
else:
print('nBad luck dumbass, the answer is %s' %(result))
break
except ValueError:
print('nValue must be an integer')
userResult = input('Solve %s' %(questionString))
return score    

需要"dedent"游戏类中的函数:

class Game:
def __init__ (self, noOfQuestions = 0):
self._noOfQuestions = noOfQuestions # the underscored argument has property definitions
# -------------------------------------------------------------
# following function moved backward at same level as __init__()
# -------------------------------------------------------------
@property # returns one as the other when queried
def noOfQuestions(self):
print('getter')
return self._noOfQuestions
@noOfQuestions.setter # to set the value it needs to meet the parameters below
def noOfQuestions(self, value):
print('1st line')
if value < 1:
print('2nd line')
self._noOfQuestions = 1
print('The minimum number of questions is one, so there will be one.')
elif (value > 10):
print('3rd line')
self._noOfQuestions = 10
print('The maximum number of questions is ten, so there will be ten.')
else :
print('4th line')
self._noOfQuestions = value

这是一个缩进问题,getter/setter是在__init__函数中定义的。

你需要取消:

class Game:
def __init__(self, noOfQuestions=0):
self._noOfQuestions = noOfQuestions  # the underscored argument has property definitions
# <!-- UNINDENT HERE, LIKE THIS: -->
@property  # returns one as the other when queried
def noOfQuestions(self):
print('getter')
return self._noOfQuestions
@noOfQuestions.setter  # to set the value it needs to meet the parameters below
def noOfQuestions(self, value):
print('1st line')
if value < 1:
print('2nd line')
self._noOfQuestions = 1
print('The minimum number of questions is one, so there will be one.')
elif value > 10:
print('3rd line')
self._noOfQuestions = 10
print('The maximum number of questions is ten, so there will be ten.')
else:
print('4th line')
self._noOfQuestions = value

最新更新