python - flask 开发中这里的seed()方法有什么用?
怪我咯
怪我咯 2017-04-17 17:30:45
[Python讨论组]
class User(UserMixin, db.Model):
         # ...
    @staticmethod
    def generate_fake(count=100):
             from sqlalchemy.exc import IntegrityError
             from random import seed
             import forgery_py
             seed()
             for i in range(count):
                 u = User(email=forgery_py.internet.email_address(), username=forgery_py.internet.user_name(True), password=forgery_py.lorem_ipsum.word(), confirmed=True, name=forgery_py.name.full_name(), location=forgery_py.address.city(), about_me=forgery_py.lorem_ipsum.sentence(), member_since=forgery_py.date.date(True))
                 db.session.add(u)
                 try:
                     db.session.commit()
                 except IntegrityError:
                     db.session.rollback()
                     
 class Post(db.Model):
         # ...
  @staticmethod
  def generate_fake(count=100):
         from random import seed, randint
         import forgery_py
         seed()
         user_count = User.query.count()
         for i in range(count):
            u = User.query.offset(randint(0, user_count - 1)).first()
            p = Post(body=forgery_py.lorem_ipsum.sentences(randint(1, 3)),
                      timestamp=forgery_py.date.date(True),
                      author=u)
            db.session.add(p)
            db.session.commit()
            
            
           
           
           seed()方法不是里面加了参数才能让随机结果相同吗?这里在两个方法上调用是为什么呢?这个是《Flask Web 开发》里的一个实例
怪我咯
怪我咯

走同样的路,发现不同的人生

全部回复(1)
高洛峰

这个是python标准库里内置的随机数种子,不但python有,C,java里面也有,可以认为是系统提供的一个接口,一般随机数都是一个伪随机数,使用种子之后,能在概率上产生近似的随机数值,这个结论见
http://www.zhihu.com/question/34606275

http://blog.chinaunix.net/xmlrpc.php?r=b...

是这样的,伪随机数的生成一般依赖于对每个初始值做操作,这里的某个初始值一般是由生成器生成的,这个初始值一般会根据当前时间产生,所以你在不同的时间调用,产生的值是不同的,如果你使用相同的种子,则产生的随机数是相同的。
写了个例子,你看下。

# -*- coding: utf-8 -*-

import random
random.seed(5)  # 这里不再试用无参数的seed,而是指定一个数

print random.random()

random.seed(5) # 这里不再试用无参数的seed,而是指定一个数
print random.random()

你可以看下,两次的random结果是一样的.附上random.seed的手册

random.seed([x ])

Initialize the basic random number generator. Optional argument x can be any hashable object. If x is
omitted or None, current system time is used; current system time is also used to initialize the generator
when the module is first imported. If randomness sources are provided by the operating system, they are
used instead of the system time (see the os.urandom() function for details on availability).
Changed in version 2.4: formerly, operating system resources were not used.

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号