问题描述
我正在使用python中的Building Skills in Object Oriented Design,正在wheel section上进行轮盘赌。我们已经创建了一个“ Bin”类,作为frozenset的扩展类,它将代表轮盘上的每个位置。然后,我们创建一个包含38个空“容器”的元组,现在必须创建类方法才能向容器添加赔率/结果。
我的问题是我无法创建一种方法来修改Bin的位置,而结果不会恢复为Frozenset类。
我想要的输出是:
class Bin(frozenset):
def add(self,other):
....do union of Bin class....
one = Bin(1,2,3)
two = Bin(4,5)
one.add(two)
print(one)
>>> Bin(1,3,4,5)
我尝试过的东西
在未定义/覆盖任何方法的情况下扩展Frozenset类
class Bin(frozenset):
pass
one = Bin([1,3])
two = Bin([4,5,6])
print(one|two)
print(type(one|two))
返回哪个
frozenset({1,6})
<class 'frozenset'>
我希望通过扩展该类并使用扩展方法之一,将输出保留为“ Bin”类。
我也尝试过以相同的结果重写__ ror__和union方法。我尝试创建一种暴力破解返回所需输出的方法。但是,这不允许我更改Bins的元组,因为它未就位运行
class Bin(frozenset):
def add(self,other):
self = Bin(self|other)
return self
one = Bin([1,6])
one.add(two)
print(one)
返回哪个
Bin({1,3})
任何深入了解我的思想的想法和/或建议阅读以进一步了解的东西的建议都是很好的。
解决方法
您需要执行以下操作(以避免无限递归):
class Bin(frozenset):
def __or__(self,other):
return Bin(frozenset(self) | other)
,
frozenset.__or__
(由Bin.__or__
“触发”时由one | two
的默认实现调用)不知道frozenset
被Bin
子类化了,并应返回一个Bin
实例。
您应该实现Bin.__or__
并强制其返回一个Bin
实例:
class Bin(frozenset):
def __or__(self,other):
# be wary of infinite recursion if using | incorrectly here,# better to use the underlying __or__
return Bin(super().__or__(other))
one = Bin([1,2,3])
two = Bin([4,5,6])
print(one | two)
print(type(one | two))
输出
Bin({1,3,4,6})
<class '__main__.Bin'>