我如何在另一个函数中调用一个函数?

问题描述 投票:-1回答:3

我只想在dice类中创建一个单独的函数,这将使我可以将'rolls'函数的list_of_rolls列表中的每个'roll'存储在其中。因此,当调用“ rolls”时,它将显示每个执行的“ roll”的列表(如果有的话)。

我尝试过使用global,但是没有用(也许我做错了),我也听说使用global是一种坏习惯,所以如果我不介意的话。我的缩进是正确的,只是这里没有显示。

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
python function dice
3个回答
0
投票

将list_of_rolls声明为类的成员变量,而不是在函数中定义它。创建一个构造函数以对其进行初始化。如果您在类名称之后执行此操作,则它将成为该类的名称,而不是在实例级别。

import random
class Dice:
    # list_of_rolls = [] # becomes class variable and dont use it

    def __init__(self):
         self.list_of_rolls = []        

    def roll(self):

0
投票

您应该通过调用函数rollsroll中掷骰子

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,times):
    return [self.roll() for _ in range(times)]


print(Dice().rolls(7))

0
投票

有几种方法可以做到这一点。但是,我仅建议最直接的方法是在Dice类本身中引入一个变量。

import random

class Dice:
    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
    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
© www.soinside.com 2019 - 2024. All rights reserved.