独立的“随机"实例 [英] Independent instances of 'random'

查看:76
本文介绍了独立的“随机"实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码试图说明我想要的.我基本上希望两个相互独立运行的随机"实例.我想在一个类中植入随机",而又不影响另一类中的随机".我该怎么办?

class RandomSeeded:
    def __init__(self, seed):
        import random as r1
        self.random = r1
        self.random.seed(seed)
    def get(self):
        print self.random.choice([4,5,6,7,8,9,2,3,4,5,6,7,])

class Random:
    def __init__(self):
        import random as r2
        self.random = r2
        self.random.seed()
    def get(self): 
        print self.random.choice([4,5,6,7,8,9,2,3,4,5,6,7,])

if __name__ == '__main__':
    t = RandomSeeded('asdf')
    t.get()       # random is seeded within t
    s = Random()
    s.get()       
    t.get()       # random should still be seeded within t, but is no longer

解决方案

random.Random存在的目的是为了允许您想要的行为-模块本质上是单例,但是类必须被多重实例化,因此这两种需求被覆盖.

如果您需要模块的独立副本(在random的情况下绝对不需要!),请尝试在其上使用copy.deepcopy-在许多情况下它将起作用.但是,这种需求非常少见,因为模块通常不保留全局可变状态,除非通过保留它们也为外部消耗"提供的类的一个特权实例(random之外的其他示例包括fileinput).

The below code attempts to illustrate what I want. I basically want two instances of "random" that operate independently of each other. I want to seed "random" within one class without affecting "random" in another class. How can I do that?

class RandomSeeded:
    def __init__(self, seed):
        import random as r1
        self.random = r1
        self.random.seed(seed)
    def get(self):
        print self.random.choice([4,5,6,7,8,9,2,3,4,5,6,7,])

class Random:
    def __init__(self):
        import random as r2
        self.random = r2
        self.random.seed()
    def get(self): 
        print self.random.choice([4,5,6,7,8,9,2,3,4,5,6,7,])

if __name__ == '__main__':
    t = RandomSeeded('asdf')
    t.get()       # random is seeded within t
    s = Random()
    s.get()       
    t.get()       # random should still be seeded within t, but is no longer

解决方案

Class random.Random exists specifically to allow the behavior you want -- modules are intrinsically singletons, but classes are meant to be multiply instantiated, so both kinds of needs are covered.

Should you ever need an independent copy of a module (which you definitely don't in the case of random!), try using copy.deepcopy on it -- in many cases it will work. However, the need is very rare, because modules don't normally keep global mutable states except by keeping one privileged instance of a class they also offer for "outside consumption" (other examples besided random include fileinput).

这篇关于独立的“随机"实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆