簡體   English   中英

將 OR 語句分配給 python 中的變量

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

我一直在尋找將or語句分配給變量的方法,以便該變量可以用作其他比較的參考。

我想通過示例完成什么:

a = 1
b = 0

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

您可以通過創建一個 class 並將您的 integer 值替換為包含每個 integer 的對象來更改==運算符的定義,這樣您就可以使用__eq__ function 覆蓋等於運算符。在這個例子中,我將否定結果的默認運算符向您展示您可以應用該操作所需的任何定義。 唯一的缺點是在 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)

您可以使用functools.partialoperator.or_獲得類似的東西:

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

但要注意, ab在定義時被評估:

a=False
c()
True

你似乎想要的是有點接近集合的工作方式,使用運算符| 替換or (不能被覆蓋):

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

您原則上可以制作自己的 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

但值得懷疑的是,由此產生的混亂代碼是否值得。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM