我需要在Python中创建一个'容器'对象或类,它保存我也定义的其他对象的记录.该容器的一个要求是,如果认为两个对象相同,则移除一个(任一个).我的第一个想法是使用a set([])作为包含对象,来完成这个要求.
但是,该集不会删除两个相同对象实例中的一个.我必须定义什么来创建一个?
这是Python代码.
class Item(object):
def __init__(self, foo, bar):
self.foo = foo
self.bar = bar
def __repr__(self):
return "Item(%s, %s)" % (self.foo, self.bar)
def __eq__(self, other):
if isinstance(other, Item):
return ((self.foo == other.foo) and (self.bar == other.bar))
else:
return False
def __ne__(self, other):
return (not self.__eq__(other))
Run Code Online (Sandbox Code Playgroud)
翻译员
>>> set([Item(1,2), Item(1,2)])
set([Item(1, 2), Item(1, 2)])
Run Code Online (Sandbox Code Playgroud)
很明显__eq__(),被调用的x == y不是集合调用的方法.什么叫?我还必须定义什么其他方法?
注意:Items必须保持可变,并且可以更改,因此我无法提供__hash__()方法.如果这是唯一的方法,那么我将重写使用不可变的Items.
任何人都可以为Python推荐一个Socket.IO客户端库吗?我已经浏览了一下,但我能找到的唯一一个是服务器实现,或者依赖于像Twisted这样的框架.
我需要一个不依赖于其他框架的客户端库.
仅仅使用众多连接类型之一是不够的,因为python客户端需要使用多个socketio服务器,例如,其中许多服务器不支持websockets.
在javascript中编写以下函数有两种功能相同的方法,哪种更好或更有效,为什么?
(str) ->
s = 0
for i in [0...str.length]
s += str.charCodeAt i
s
Run Code Online (Sandbox Code Playgroud)
要么
(str) ->
s = 0
for i in str
s += i.charCodeAt 0
s
Run Code Online (Sandbox Code Playgroud)
旁白:你能建议其他任何方法吗?
编辑:根据JSPerf,第一个更快:http://jsperf.com/coffee-for-loop-speed-test - 这是为什么?
python ×3
coffeescript ×1
comparison ×1
go ×1
javascript ×1
loops ×1
methods ×1
set ×1
socket.io ×1