我是Python的新手。无论如何,我试图制作21个问题的游戏,但我的代码不起作用。
错误是:Name 'plux' is not defined.
以下是代码:
from random import randint
class Game(object):
num = randint(1, 3)
def plux(x):
x += 1
return x
def minu(x):
x -= 1
def iff(i):
apple = 0
num = randint(1, 3)
if num == 1:
x = input('Can you eat it? ').lower()
if x == "yes" or "yeah":
print("test num 1")
apple = plux(apple)
elif num == 2:
print('test num 2')
elif num == 3:
print("test num 3")
a = Game()
print(a.iff())
答案 0 :(得分:0)
当您在行plux
中调用apple = plux(apple)
函数时,请在函数调用前添加self.
。在Python中,self.
用作对类本身(在Game
类中的任何位置)内使用的对象本身的引用。在课程的每个功能中,self
必须是第一个参数(这是我不知道为什么必须做的事情,我确定有理由,但只需按照这个惯例仔细)。
答案 1 :(得分:0)
该课程应如下所示(缺少自我):
from random import randint
class Game(object):
def __init__(self):
self.num = randint(1, 3)
self.x=0
def plux(self):
self.x += 1
def minu(self):
self.x -= 1
def iff(self):
apple = 0
self.num = randint(1, 3)
if self.num == 1:
x = raw_input('Can you eat it? ').lower()
if x == "yes" or "yeah":
print("test num 1")
apple = self.plux()
elif self.num == 2:
print('test num 2')
elif self.num == 3:
print("test num 3")
a = Game()
a.iff()