小编hug*_*o24的帖子

创建可以看到当前类方法的装饰器

你能在类中创建一个装饰器来查看类方法和变量吗?

这里的装饰者没有看到:self.longcondition()

class Foo:
    def __init__(self, name):
        self.name = name

    # decorator that will see the self.longcondition ???
    class canRun(object):
            def __init__(self, f):
                self.f = f

            def __call__(self, *args):
                if self.longcondition(): # <-------- ???
                    self.f(*args)

    # this is supposed to be a very long condition :)
    def longcondition(self):
        return isinstance(self.name, str)

    @canRun # <------
    def run(self, times):
        for i in xrange(times):
            print "%s. run... %s" % (i, self.name)
Run Code Online (Sandbox Code Playgroud)

python decorator class-method

4
推荐指数
1
解决办法
351
查看次数

在python 2.6和python 2.7上使用随机的不同浮点精度

在Python 2.6和Python 2.7中使用Random.random()时,为什么会有不同的精度

例:

import random
import sys

rng = random.Random(0)

print sys.version
for i in range(10):
    print repr(rng.random())
Run Code Online (Sandbox Code Playgroud)

2.6.6(r266:84297,2010年8月24日,18:46:32)[MSC v.1500 32 bit(Intel)]
0.84442185152504812
0.75795440294030247
0.420571580830845

2.7.5(默认,2013年5月15日,
22:
43:
36 )[MSC v.1500 32 bit(Intel)] 0.8444218515250481 0.7579544029403025 0.420571580830845

为什么有不同的精度?可能是因为这种变化:http: //docs.python.org/2/tutorial/floatingpoint.html#representation-error

在Python 2.7和Python 3.1之前的版本中,Python将此值四舍五入为17位有效数字,给出"0.10000000000000001".在当前版本中,Python显示一个基于最小小数的值,该小数正确地回滚到真正的二进制值,结果只是'0.1'.

python random floating-point-precision

1
推荐指数
1
解决办法
499
查看次数