Skip to main content
 首页 » 编程设计

python之Python生成随机数时的属性错误

2025年05月04日13jillzhang

我之前就同一段代码问过一个类似的问题,但我又一次发现自己被卡住了。特别是在生成包含两个字母、两个数字和两个字母的车牌时。我希望这个问题不是重复的,但在这种情况下我很困惑该怎么做,这是到目前为止的代码,我希望你能确定我哪里出错了:

from datetime import date, datetime, time, timedelta 
import time, string 
from random import uniform, random 
 
def timeDelta(): 
    print("Average Speed Checker") 
    start = (input("Car has passed Cam1: ")) 
    licensePlate = str(firstLetters + randomNumber + " " + secondLetters) 
    print(licensePlate) 
    if start in ("y"): 
        camInput1 = datetime.now() 
        print(camInput1) 
        print("Car is travelling...") 
        time.sleep(1) 
        print("Car is travelling...") 
        time.sleep(1) 
        print("Car has passed cam2") 
        camInput2 = camInput1 + timedelta(seconds = uniform(5, 10)) 
        timeDelta = camInput2 - camInput1 
        distance = 200 
        duration = timeDelta.total_seconds() 
        print("Time Delta is equal to: {0}".format(duration)) 
        speedCarMs = distance/duration 
        print("Car is travelling in m/s at: {0}".format(speedCarMs)) 
        speedCarMph = 2.237*speedCarMs 
        print("Car is travelling in MPH at: {0}".format(speedCarMph)) 
        if speedCarMph > 60: 
            fileInput: 
 
def possibleNumber(): 
    possibleNumbers = (1,2,3,4,5,6,7,8,9,0) 
    randomNumber = random.sample(possibleNumbers, 2) 
 
def randomLetters1(y): 
    return ''.join(random.choice(string.ascii_uppercase) for x in             range(y)) 
firstLetters = (randomLetters1(2)) 
secondLetters = (randomLetters1(3)) 
 
print("Choose which function you want to use: ") 
while True: 
    answer = (input("Choice: ")) 
    if answer in ("speed"): 
        timeDelta() 
else: 
    print("Invalid response") 

根据python,问题是这样的:

AttributeError: 'builtin_function_or_method' object has no attribute 'choice' 

请您参考如下方法:

您没有导入 random 模块。您导入了 random.random() 函数:

from random import uniform, random 

如果您想同时使用 choice() 和 sample(),请另外导入:

from random import uniform, random, choice, sample 

并调整您对这些功能的使用:

def possibleNumber(): 
    possibleNumbers = (1,2,3,4,5,6,7,8,9,0) 
    randomNumber = sample(possibleNumbers, 2) 
 
def randomLetters1(y): 
    return ''.join(choice(string.ascii_uppercase) for x in range(y)) 

或者,只导入模块:

import random 

并且您的代码将正常工作,因为您实际上并没有在任何地方使用 random(),前提是您将 uniform() 替换为 random.uniform():

camInput2 = camInput1 + timedelta(seconds = random.uniform(5, 10)) 

我再次重申,您不需要创建 camInput2,因为 camInput1 + some_timedelta - camInput1 产生与 some_timedelta 相同的值>;你可以只使用:

timeDelta = timedelta(seconds = random.uniform(5, 10)) 

您永远不会调用 randomNumbers() 函数,该函数也不会返回 任何东西。该函数中的 randomNumber 局部名称在函数外部不可用。

让函数返回结果并使用函数,您现在尝试通过 randomNumber 名称使用结果:

def possibleNumber(): 
    possibleNumbers = (1,2,3,4,5,6,7,8,9,0) 
    return random.sample(possibleNumbers, 2) 

和

licensePlate = str(firstLetters + possibleNumber() + " " + secondLetters)