我对python和编码一般都很陌生,对不起,如果这个问题对大多数人来说都很简单。我正在尝试编写一个生成代码的小程序,基本上你有猜测正确代码的infinte猜测。一旦我把它弄下来,我计划按数字进行编号,所以你只需猜测第一个数字,直到你得到正确的数字,然后是第二个数字,依此类推......现在我只是在玩我的东西到目前为止已经写了,我只是试图让代码在开始时显示,但它没有成功,因为它说“对象没有属性'代码'。”我希望有人可以指出我的错误。
Tracker.py
from Number import *
class Runner(object):
def __init__(self, start):
self.start = start
print Integer.__doc__
print Integer.code
def play(self):
next_guess = self.start
Integer = Random_Integer()
Guess = Runner(Integer)
Guess.play()
Number.py
from random import randint
class Random_Integer(object):
"""Welcome to the guessing game! You have unlimited attempts
to guess the 3 random numbers, thats pretty much it.
"""
def __init__(self):
code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9))
答案 0 :(得分:3)
您正在尝试打印code
方法的属性Integer.__init__
。该属性不存在。
函数的局部变量未公开;您无法访问code
,除非您将其设为实例属性:
class Random_Integer(object):
"""Welcome to the guessing game! You have unlimited attempts
to guess the 3 random numbers, thats pretty much it.
"""
def __init__(self):
self.code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9))
然后
class Runner(object):
def __init__(self, start):
self.start = start
print start.__doc__
print start.code
答案 1 :(得分:0)
为了使code
成为Random_Integer类的实例变量,您需要在self.code
中使用__init__()