Python 如何在一个函数中调用另一个函数?
我只想在dice类中创建一个单独的函数,它允许我在“rolls”函数中存储“rolls”列表中的每个“roll”。因此,当调用“rolls”时,它将显示执行的每个“roll”的列表(如果有) 我试过使用global,但它不起作用(也许我做错了),我还听说使用global是一个坏习惯,所以如果有其他方法,我不会介意。我的缩进是正确的,只是这里没有显示Python 如何在一个函数中调用另一个函数?,python,function,dice,Python,Function,Dice,我只想在dice类中创建一个单独的函数,它允许我在“rolls”函数中存储“rolls”列表中的每个“roll”。因此,当调用“rolls”时,它将显示执行的每个“roll”的列表(如果有) 我试过使用global,但它不起作用(也许我做错了),我还听说使用global是一个坏习惯,所以如果有其他方法,我不会介意。我的缩进是正确的,只是这里没有显示 import random class Dice: def roll(self): x = random.randin
import random
class Dice:
def roll(self):
x = random.randint(1, 6)
y = random.randint(1, 6)
roll_list = (x, y)
return roll_list
def rolls(self):
list_of_rolls = []
final = list_of_rolls.append()
return final
将\u rolls的列表\u声明为类的成员变量,而不是在函数中定义它。创建一个构造函数来初始化它。如果您在类名之后执行此操作,则它将成为该类的一部分,而不是在实例级别
import random
class Dice:
# list_of_rolls = [] # becomes class variable and dont use it
def __init__(self):
self.list_of_rolls = []
def roll(self):
有几种方法可以做到这一点。然而,我只是想建议一种最直接的方法,即使用文本文件在骰子类本身中存储您的掷骰历史记录。 请注意,con将多个Dice实例将访问同一历史文件 但是,此实现可能不会得到优化,因为每次掷骰子时,您都在打开文件并向其添加新的骰子。如果你需要数百万卷,这可能并不理想。也就是说,我将让您改进/优化解决方案
import random
class Dice:
list_of_rolls = []
filename = "./roll_history.txt" # a textfile to store history of rolls
def __init__(self):
try: # just to check if file exists if not create one for storing
file = open(self.filename, "r")
except FileNotFoundError:
print("File not found")
file = open(self.filename, "x") #creates file
finally:
file.close()
with open(self.filename, 'r') as opened_file_object:
self.list_of_rolls = opened_file_object.read().splitlines()
print(self.list_of_rolls)
def roll(self):
x = random.randint(1, 6)
y = random.randint(1, 6)
roll_list = (x, y)
self.list_of_rolls.append(roll_list) # updates the array with latest roll
file = open(self.filename, 'a') # 'a' for appending new rolls
# I append a newline so that the rolls are more readable in the text file
file.write('(' + str(x) + ',' + str(y) + ')\n') # appends a newline
return roll_list
def rolls(self):
return self.list_of_rolls
print(Dice().roll()) # append 2 dice rolls here
print(Dice().roll())
print(Dice().rolls()) # you should see 2 dice rolls here
尝试关闭python程序并再次运行,
这几乎是我想要的,但我一直在努力,仍然感到困惑。我希望rolls函数也声明过去的所有rolls,因此如果我运行代码两次,它将显示两次代码运行中的所有rolls。在你给我的解决方案中(我很感激),每次我运行代码时它都会重置。让我澄清一下……你希望你的程序运行一些骰子,存储它们,然后关闭程序。下次运行程序并使用rolls()时,它将返回所有以前的骰子掷骰?我希望rolls函数也声明过去的所有掷骰,因此,如果我运行代码两次,它将显示两次代码运行中的所有掷骰。不仅仅是目前的情况。我已经试了几个小时了,但我想不出来。因此,
list\u卷
将累加运行的每个roll
。
Dice() # you should be able to see past rolls