变量值由函数调用确定

这可能很奇怪,但我想声明一个没有固定值的变量,但是以某种方式“链接”到函数的结果。 目标是让最终用户操纵变量,但每次使用变量的值时,其值可能会改变。

这是我得到的最新结果:

from random import randint

def randomfun():
    return randint(1, 100)

an_int = randomfun
print an_int    # Print the function object
print an_int()  # Print the result of randomfun()

我想得到的是print an_int实际调用randomfun() ,但不必添加括号,并且an_int的类型应该是randomfun的返回类型。


an_int是一个对象。 除非你改变它,它不会改变它的价值。 但是,您可以更改对象的表示方式:

from random import randint

class RandomFun(object):
    def __str__(self):
        return str(randomfun())

def randomfun():
    return randint(1, 100)

an_int = RandomFun()
print an_int    
print an_int    

产量(类似)

57
19
链接地址: http://www.djcxy.com/p/75507.html

上一篇: Variable value is determined by function call

下一篇: Divide Sphinx TOC into subsections with subheadings