【发布时间】:2014-02-17 11:50:12
【问题描述】:
我正在做这个小练习... 我想根据一些奇怪的字典重新排序一个字符串。 例如,根据我的字典,字母按顺序排列: “a”、“b”、“d”、“c”、“f”、“e”
所以我想我应该为字符串重载
这里是:
class MyString(str):
new_dict = dict((x,i) for i,x in enumerate(["a", "b", "d", "c", "f", "e"]))
def __lt__(self,other):
return self.new_dict[self] < self.new_dict[other]
def __init__(self,x):
str.__init__(self,x)
然后
In [59]: sorted((MyString(x) for x in "abcdef"))
Out[59]: ['a', 'b', 'd', 'c', 'f', 'e']
太棒了。甚至:
In [64]: MyString("".join(sorted((MyString(x) for x in "abcdef"))))
Out[64]: 'abdcfe'
但为什么我不能只做sorted(MyString("abcdef"))?
In [70]: sorted(MyString("abcdef"))
Out[70]: ['a', 'b', 'c', 'd', 'e', 'f']
显然 MyString 的迭代器正在返回字符串。
In [72]: for i in MyString("abcdef"):
print type(i)
....:
<type 'str'>
<type 'str'>
<type 'str'>
<type 'str'>
<type 'str'>
<type 'str'>
如果我在 MyString 上调用 join 会发生什么:
In [63]: type(MyString("").join(sorted((MyString(x) for x in "abcdef"))))
Out[63]: str
为什么 MyString 有 str 迭代器?
【问题讨论】:
-
sorted()采用一个关键函数,让您可以为已排序的元素定义排序值。 -
否则,排序使用
>、>=、<=和==同样需要提供all运算符。
标签: python inheritance operator-overloading