简体   繁体   中英

Redefine `False` in Python2? How to assign a function call to a variable name?

There isn't any reason in particular that I wish to do this, I just wanted to see False be True every once in a while.

import random
def dice():
    return random.randint(1,3)==2 
False = dice()

This will not give me what I want--I imagine False being initialized to some value as dice() is called, and thus remaining as that value thereon. How can I make it so that each time I check the value of False, it is as if I have called dice() ?

If anyone has a better way to phrase this please feel free to provide an edit. Thanks.

You cannot do that in either Python 2 or 3. You can assign a value to False in Python 2, but what you can't do is make it so that just reading the value of a plain variable ( False or anything else) calls a function.

You can do it if the thing you're reading is not a bare-name variable but some kind of expression (like an attribute access). That is, you can make it so that something like ab evaluates to a different value every time, but not so that just plain a evaluates to a different value every time.

To do this, you need more control over the name lookup procedure than Python ordinarily gives you. You need to execute the code in a namespace that uses name lookup rules you control, which means you have to use exec :

import random

class WeirdLocals(dict):
    def __getitem__(self, index):
        if index == 'False':
            return random.choice([True, False])
        return super(WeirdLocals, self).__getitem__(index)

exec '''
print False # Might print True
print False # Might print True
print False # Might print True
''' in globals(), WeirdLocals()

Note that functions defined inside an exec will ignore the provided locals for name lookup, and even if you try to provide a global dict with a weird __getitem__ override, they might bypass it anyway.

If you can tolerate having to use . in your variable name, the @property decorator can give you want you want.

Example:

import random

class Foo:
     def __init__(self):
             pass
     @property
     def True(self):
             return random.choice([True,False,True])

And then if you do

 F=Foo() 
 print(F.True) #will return True 66% of the time and False 33% of
 the time.

You can't do that with just False ; if you're calling a function, you need to use the function syntax. You could do

False = dice
...
if my_value == False():
    ... action

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