简体   繁体   English

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

[英]Attribute error when generating random numbers in Python

I asked a similar question regarding this same piece of code earlier but once again I have found myself stuck.我之前就同一段代码问了一个类似的问题,但我再次发现自己被卡住了。 Particularly on the generation of a license plate containing two letters, two numbers, and then two letters.特别是生成包含两个字母、两个数字和两个字母的车牌。 I hope that this question isn't a duplicate but in this circumstance I am very stuck with what to do, this is the code so far and I hope you can identify where I am going wrong:我希望这个问题不是重复的,但在这种情况下,我非常坚持要做什么,这是到目前为止的代码,我希望您能确定我哪里出错了:

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")

According to python, the issue is to do with this:根据python,问题与此有关:

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

You did not import the random module.您没有导入random模块。 You imported the random.random() function :您导入了random.random()函数

from random import uniform, random

If you wanted to use choice() and sample() as well, import that in addition:如果您还想使用choice()sample() ,请另外导入:

from random import uniform, random, choice, sample

and adjust your use of those functions:并调整您对这些功能的使用:

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))

Or, instead, import just the module :或者,相反,导入模块

import random

and your code will work as you don't actually use random() anywhere, provided you replace uniform() with random.uniform() :并且您的代码将起作用,因为您实际上并未在任何地方使用random() ,前提是您将uniform()替换为random.uniform()

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

I'll reiterate again that you don't need to create camInput2 , as camInput1 + some_timedelta - camInput1 produces the same value as some_timedelta ;我会再次重申,你不需要创建camInput2 ,作为camInput1 + some_timedelta - camInput1产生相同的值some_timedelta ; you can just use:你可以使用:

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

You never call the randomNumbers() function, nor does the function return anything.您从不调用randomNumbers()函数,该函数也不返回任何内容。 The randomNumber local name in that function is not available outside of the function.该函数中的randomNumber本地名称在该函数之外不可用。

Have the function return the result and use the function where you now try to use the result via the randomNumber name:让函数返回结果并使用现在尝试通过randomNumber名称使用结果的randomNumber

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

and

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

random.random , which you refer to in your code as simply random , because you imported it directly into your namespace ( from random import ... random ) instead of importing the entire module ( import random ), is a free function, which does not have an attribute named choice . random.random ,您在代码中简称为random ,因为您将其直接导入到您的命名空间( from random import ... random )而不是导入整个模块( import random ),是一个免费函数,它不会没有名为choice的属性。

For the code you've written, calling random.choice , and random.sample , your import statement should be import random .对于您编写的调用random.choicerandom.sample ,您的导入语句应该是import random Alternatively, switch your function calls to simply choice(...) and sample(...) ...或者,将您的函数调用切换为简单的choice(...)sample(...) ...

I encountered the same issue when one day my code stopped working because of this same error.当有一天我的代码因为同样的错误而停止工作时,我遇到了同样的问题。 Reading the other answers i came up with this workaround: Give an alias to the random module, so that when you call the alias.choice method there is no ambiguity:阅读其他答案我想出了这个解决方法:给随机模块一个别名,这样当你调用 alias.choice 方法时就没有歧义:

import json,random as rd, string
from random import uniform, random, choice, sample

def randomString(stringLength):
    letters = string.ascii_letters
    return ''.join(rd.choice(letters) for i in range(stringLength))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM