我正在做 Cesare Rocchi 的教程“如何创建基于套接字的 iPhone 应用程序和服务器”http://www.raywenderlich.com/3932/how-to-create-a-socket-based-iphone-app-and-server#comments
我是否需要在“class IphoneChat(Protocol)”中定义一个名为“name”的属性,还是从“twisted.internet.protocol”继承?如果是继承的,如何正确访问?
服务器.py:
from twisted.internet.protocol import Factory, Protocol
from twisted.internet import reactor
class IphoneChat(Protocol):
def connectionMade(self):
self.factory.clients.append(self)
print "clients are", self.factory.clients
def connectionLost(self, reason):
self.factory.clients.remove(self)
def dataReceived(self, data):
a = data.split(':')
print a
if len(a) > 1:
command = a[0]
content = a[1]
msg = ""
if command == "iam":
self.name = content
msg = self.name + "has joined"
elif command == "msg":
msg = self.name + ": " + content
print msg
for c in self.factory.clients:
c.message(msg)
def message(self, message):
self.transport.write(message + '\n')
factory = Factory()
factory.protocol = IphoneChat
factory.clients = []
reactor.listenTCP(80, factory)
print "Iphone Chat server started"
reactor.run()
终端输出:
Iphone Chat server started
...
--- <exception caught here> ---
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/twisted/internet/selectreactor.py", line 150, in _doReadOrWrite
why = getattr(selectable, method)()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/twisted/internet/tcp.py", line 199, in doRead
rval = self.protocol.dataReceived(data)
File "server.py", line 30, in dataReceived
msg = self.name + ": " + content
exceptions.AttributeError: IphoneChat instance has no attribute 'name'
到目前为止解决问题的步骤:
- 我在 self.factory.clients 列表中读到“name”是托管服务器端,但后来我查找了twisted.internet.protocol 的类定义,却发现没有像“name”http://twistedmatrix.com/documents/11.0.0/api/twisted.internet.protocol.Protocol.html 这样的内容。
- 根据我在其他地方读到的内容,这可能只是一个缩进错误。
最佳答案
这个错误是很符合逻辑的
if command == "iam":
self.name = content
msg = self.name + "has joined"
elif command == "msg":
msg = self.name + ": " + content
print msg
在第一个 if 子句中,您为 self.name 分配了一个值,这可能依赖于 self.name 存在于某处的假设,或者假设它是新的并且需要声明,但在 elif 中,您似乎假设确定 self.name 已经存在,但事实证明它不存在,因此您会收到错误。
我想你最安全的选择就是简单地在 dataReceived 方法的开头添加 self.name :
def dataReceived(self, data):
self.name = ""
这将消除错误。作为替代方案,您也可以将 self.name 添加到 IphoneChat 的 init 方法中。如果您不仅在 dataReceived 中,而且在其他函数中需要 self.name ,那么用 self.name 添加 init 是可行的方法,但从您的代码看来,您只在收到的数据中需要它,所以只需将其添加到那里即可。在 init 中添加 self.name 看起来像这样:
class IphoneChat(Protocol):
def __init__(self):
self.name = ""
或者你也可以简单地这样做
class IphoneChat(Protocol):
name = ""
然后继续使用 name 而不是 self.name。
关于python - 异常.AttributeError : Python instance has no attribute 'name' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18041732/