当我声明一个时,DiceGame会返回一个错误,说没有变量?

时间:2016-11-22 17:55:47

标签: python python-3.x oop syntax python-3.5

我是一名业余15岁的程序员,他对Python中的功能相对较新,从未使用过OOP Python,但是我已经深入研究了它。我们的课程项目是制作一个简单的骰子游戏,但我试图扩展我的技能。源代码将在下面,我将留下评论,我想要帮助(所以不要告诉我有一个哈希,那是让你知道我认为我出错的地方)。每当我运行程序时,控制台都会出现以下错误:

Traceback (most recent call last):
  File "python", line 5, in <module>
  File "python", line 52, in DiceGame
  File "python", line 30, in main
NameError: name 'sides' is not defined

以下是源代码:

#Jabir Hussains Source Code - Dice Task
import random

x = "Error!"

class DiceGame():
  def sides():
    sides = int(input("How many sides would you like on your di[c]e?"))
    if sides > 10:
      print("Sorry, the developer didn't have the time to program above 10 dice")
      sides = int(input("How many sides do you like on your di[c]e?"))
    elif sides < 6:
      print("The limit is 6 sides. Please try again")
      sides = int(input("How many sides do you like on your di[c]e?")) #Here I've defined the number of sides
    else:
      return sides
  sides()

  def diceNum():
    numDice = int(input("How many dice would you like?"))
    if numDice > 2:
      print("We're limited to 2 dice, please try again")
    elif numDice < 1:
      print("That is mathematically impossible. Please try again")
      numDice = int(input("How many dice would you like?"))
    else:
      return numDice
  diceNum()

  def main():
    if sides == 6 and numDice == 1:
      print("The number is",random.randint(1,6),"!")
    elif sides == 6 and numDice == 2:
      print("The numbers are",random.randint(1,6),"and",random.randint(1,6),"!")
    elif sides == 7 and numDice == 1:
      print("The number is",random.randint(1,7),"!")
    elif sides == 7 and numDice == 2:
      print("The numbers are",random.randint(1,7),"and",random.randint(1,7),"!")
    elif sides == 8 and numDice == 1:
      print("The number is",random.randint(1,8),"!")
    elif sides == 8 and numDice == 2:
      print("The numbers are",random.randint(1,8),"and",random.randint(1,8),"!")
    elif sides == 9 and numDice == 1:
      print("The number is",random.randint(1,9),"!")
    elif sides == 9 and numDice == 2:
      print("The numbers are",random.randint(1,9),"and",random.randint(1,9),"!")
    elif sides == 10 and numDice == 1:
      print("The number is",random.randint(1,10),"!")
    elif sides == 10 and numDice == 2:
      print("The numbers are",random.randint(1,10),"and",random.randint(1,10),"!")
    else:
      print(x)
  main()
DiceGame()

1 个答案:

答案 0 :(得分:1)

这里有很多错误,我不知道从哪里开始。

但主要观点是:

1)你应该从&#34; object&#34;

定义一个类
class YourClass(object):

2)你需要一个 init 方法(它有点像构造函数,看看这个)

def __init__(self, arg1, arg2):

3)为了使用类中的对象,你必须实例化它

yourObject = YourClass(arg1, arg2)

完成后,您可以这样做:

yourObject.yourFunction()

我希望这会有所帮助,但请查看文档:

https://docs.python.org/2.7/