我正在研究python中缀运算符,我发现了这个: Python:定义我自己的运算符?
很久以前就有人问过这个问题,但我找不到最近的问题。这似乎比我通常更舒服的黑客。使用这个技巧,我改变了我的代码:
if __name__ == '__main__':
of = Infix(lambda x, y: Card(Value[x], Suit[y]))
card1 = 'EIGHT' | of | 'DIAMONDS'
card2 = 'THREE' | of | 'SPADES'
card3 = 'QUEEN' | of | 'SPADES'
assert card1.suit != card2.suit
assert card3.suit == card2.suit
assert ('NINE' | of | 'HEARTS').beats('EIGHT' | of | 'HEARTS')
assert ('NINE' | of | 'HEARTS').beats('EIGHT' | of | 'HEARTS', trump=Suit.HEARTS)
assert ('NINE' | of | 'HEARTS').beats('EIGHT' | of | 'HEARTS', trump=Suit.DIAMONDS)
assert not Card(Value.NINE, Suit.HEARTS).beats(Card(Value.TEN, Suit.HEARTS))
assert not Card(Value.NINE, Suit.HEARTS).beats(Card(Value.TEN, Suit.HEARTS), trump=Suit.HEARTS)
assert not Card(Value.NINE, Suit.HEARTS).beats(Card(Value.TEN, Suit.HEARTS), trump=Suit.DIAMONDS)
assert not Card(Value.NINE, Suit.DIAMONDS).beats(Card(Value.EIGHT, Suit.HEARTS))
assert not Card(Value.NINE, Suit.DIAMONDS).beats(Card(Value.EIGHT, Suit.HEARTS), Suit.HEARTS)
assert not Card(Value.NINE, Suit.DIAMONDS).beats(Card(Value.EIGHT, Suit.HEARTS), Suit.CLUBS)
你可以看到代码在有和没有的情况下是什么样子的,我认为像这样更具可读性。尽管如此,这是一个黑客,我也不喜欢通过字符串访问枚举。我仍在考虑:
EIGHT = Value.EIGHT
SPADES = Suit.SPADES
card = Card(EIGHT, SPADES)
我甚至可以将这两种方法结合起来,并将中缀更改为:
of = Infix(lambda x,y: Card(x, y))
card = EIGHT | of | SPADES
有没有更好的方法来做 Python 3 中的中缀?值得做吗?
编辑:
assert not (NINE | of | HEARTS).beats(TEN | of | HEARTS)
assert not (NINE | of | HEARTS).beats(TEN | of | HEARTS, trump=HEARTS)
assert not (NINE | of | HEARTS).beats(TEN | of | HEARTS, trump=DIAMONDS)
assert not Card(NINE, DIAMONDS).beats(Card(EIGHT, HEARTS))
assert not Card(NINE, DIAMONDS).beats(Card(EIGHT, HEARTS), trump=HEARTS)
assert not Card(NINE, DIAMONDS).beats(Card(EIGHT, HEARTS), trump=CLUBS)
一条评论可能暗示第一个块并不比第二个块好。我可以看到那里的逻辑。这包括我认为好的整个EIGHT = Value.EIGHT
事情。(你能看出我来自编译语言领域吗?
只需让类通过工厂方法进行解析:
class Card:
# other stuff
@staticmethod
def fromstring(s):
value, of, suit = s.split()
return Card(Value[value], Suit[suit])