简体   繁体   中英

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. 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. 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(). 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.

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 = AlwaysRandom()

Now, any time you assign random, you assign a return value from 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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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