簡體   English   中英

我想在我的班級中打印一個隨機生成的數字,但不斷出現錯誤

[英]I want to print a randomly generated number inside my class but keep getting errors

嘗試從類方法打印隨機數時,出現名稱錯誤,randint 未定義。

class Deck:
    import random
    def __init__(self,choice,card = 0):
        self.choice = choice
        self.card = card
    def deck(self): 
        if self.choice == 1:
            print((randint(1,5)))

我想讓它打印一個隨機數 1-5,我可以通過創建一個分配給它的隨機數的類變量來實現結果,我仍然想知道為什么我不能只在方法中生成隨機數。

這是因為您沒有通過random模塊調用randint

使用randint的正確方法是明確地通過random模塊進行。

import random

class Deck:
    def __init__(self,choice,card = 0):
        self.choice = choice
        self.card = card
    def deck(self): 
        if self.choice == 1:
            print((random.randint(1,5)))

或者通過將randint帶入您的模塊命名空間,如

from random import randint

class Deck:
    def __init__(self,choice,card = 0):
        self.choice = choice
        self.card = card
    def deck(self): 
        if self.choice == 1:
            print((randint(1,5)))

在類中導入通常是不好的做法,但使用類函數來執行它看起來像:

class Deck:
    random = __import__('random')
    def __init__(self,choice,card = 0):
        self.choice = choice
        self.card = card
    def deck(self): 
        if self.choice == 1:
            print((self.random.randint(1,5)))

x = Deck(choice = 1)
x.deck()

您的導入語句應該在類定義之外(最好在腳本的頂部,但這不是必需的)

為了使用 randint 函數,您必須首先引用隨機庫來調用它:

import random

class Deck:
    def __init__(self,choice,card = 0):
        self.choice = choice
        self.card = card
    def deck(self):
        if self.choice == 1:
            print((random.randint(1,5)))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM