简体   繁体   English

In Python, make a variable act like a function, call a function without parentheses, alias a function as a variable, etc?

[英]In Python, make a variable act like a function, call a function without parentheses, alias a function as a variable, etc?

I am working with slightly modifying someone else's code for my needs and want to replace what is currently a fixed variable with a function.我正在根据自己的需要稍微修改别人的代码,并想用 function 替换当前的固定变量。 But adding a () to each time the variable is referenced later to get the value is simply not feasible in this situation, or would not be worth the amount of work required.但是在以后每次引用变量时添加 () 以获取值在这种情况下根本不可行,或者不值得所需的工作量。 I need a way to define a variable as a function such that while it is referenced as a variable in all further code, it actually checks what the value should be each time it is queried as if I had added parentheses to each reference.我需要一种将变量定义为 function 的方法,这样虽然它在所有进一步的代码中被引用为变量,但它实际上会在每次查询时检查该值应该是什么,就好像我在每个引用中添加了括号一样。 I do not care how this is achieved, but it should not require any changes to the code that references the former-variable.我不在乎这是如何实现的,但它不需要对引用前一个变量的代码进行任何更改。

The function in this case is random.random().在这种情况下,function 是 random.random()。 I want to make a variable always have a random value within a certain range whenever checked, WITHOUT adding parentheses to each and every time the variable is referenced.我想让一个变量在检查时总是在一定范围内有一个随机值,而不是在每次引用变量时都添加括号。 Is there any way to do this?有没有办法做到这一点? I know I'm not giving a whole lot of information about context here, but in this case the whole point is that no knowledge or adjustment of any of the other code should be required.我知道我在这里没有提供关于上下文的大量信息,但在这种情况下,重点是不需要了解或调整任何其他代码。

You could maybe get there with a class with a property.也许可以使用带有属性的 class 到达那里。

import random as r

class AlwaysRandom:
  @property
  def random(self):
    return r.random()

Then create an instance and assign it to the name random in your namespace:然后创建一个实例并将其分配给命名空间中的random名称:

random = AlwaysRandom()

Now, any time you assign random, you assign a return value from r.random():现在,任何时候你分配随机,你从 r.random() 分配一个返回值:

>>> random.random
0.1993064343052221
>>> random.random
0.9121594527461093
>>> [random.random for _ in range(5)]
[0.0800719907184344, 0.14744257667766358, 0.5809572562744559, 0.337413501046831, 0.52033363367589]

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

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