简体   繁体   English

将 OR 语句分配给 python 中的变量

[英]Assigning an OR statement to a variable in python

I have been looking for ways to assign a or statement to a variable, in a way that the variable can be used as a reference for other comparisons.我一直在寻找将or语句分配给变量的方法,以便该变量可以用作其他比较的参考。

What i'm trying to accomplish by example:我想通过示例完成什么:

a = 1
b = 0

c = a or b
print(a == c) #would return True
print(b == c) #would also return True

You can change the definition of the == operator by creating a class and replacing your integer values with objects that contain each integer, so you will be able to override the equal operator with the __eq__ function. In this example, I will negate the result of the default operator to show you that you can apply whatever definition you need for that operation.您可以通过创建一个 class 并将您的 integer 值替换为包含每个 integer 的对象来更改==运算符的定义,这样您就可以使用__eq__ function 覆盖等于运算符。在这个例子中,我将否定结果的默认运算符向您展示您可以应用该操作所需的任何定义。 The only disadvantage is that in Python, you can't override or redefine or :唯一的缺点是在 Python 中,你不能覆盖或重新定义or

class num:
    def __init__(self, n):
        self.n = n
        
    def __eq__(self, n):
        return not n==self.n

a = num(1)
b = num(0)

c = a or b
print(a == c)
print(b == c)

You can get something like that by using functools.partial and operator.or_ :您可以使用functools.partialoperator.or_获得类似的东西:

a=True
b=False
c = partial(or_, a,b)
c()
True

But beware, a and b are evaluated at definition time:但要注意, ab在定义时被评估:

a=False
c()
True

What you seem to want is somewhat close to the way sets work, with the operator |你似乎想要的是有点接近集合的工作方式,使用运算符| replacing or (which cannot be overridden):替换or (不能被覆盖):

a = {0}
b = {1}
c = a | b     # or a.union(b)
a.issubset(c)   # True
b.issubset(c)   # True
{3}.issubset(c)   # False

You could in principle make your own class that extends set :您原则上可以制作自己的 class 来扩展set

class Singleton(set):
    def __init__(self, n):
        super().__init__([n])    
        
    def __eq__(self, other):
        return self.issubset(other) or other.issubset(self)
    
a = Singleton(1)
b = Singleton(0)
c = a | b
print(a == c) # True
print(b == c) # True

But it is doubtful whether the confusing code this generates would ever be worth it.但值得怀疑的是,由此产生的混乱代码是否值得。

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

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