我遇到了一个奇怪的错误。
import socket
from string_message_converter import StringMessageConverter as SMC
from sbe_message_converter import SBEMessageConverter
from abstract_publisher import AbstractFoo
import config
class Foo(AbstractFoo):
def __init__(self, p_id):
self.sock = 1
self.p_id = p_id
def connect(self):
ttl = 2
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl)
我有一个依赖这个类的main方法。当我运行connect()时,我得到一个NameError'全局名称' sock'未定义'。但袜子不是全球性的;它是我在__init__中定义的属性。奇怪的是,p_id不会发生同样的错误。例如:
MulticastPublisher.py:
class Foo(AbstractFoo):
def __init__(self, p_id):
self.sock = 1
self.p_id = p_id
def connect(self):
ttl = 2
self.p_id = 2
print self.p_id
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl)
将打印' 2'对于p_id(仍然会像以前一样在连接中的self.sock中断)。此外,我在不同的机器上运行相同的代码,它运行正常。为什么自我认识不被认可?
编辑:主要方法只有两行。
testmain_pub.py
def main():
f = Foo()
f.start_process() #references connect method
堆栈跟踪只是引用连接方法:
File "testmain_pub.py", line 21, in <module>
main()
File "testmain_pub.py", line 9, in main
m.publish_start("start message")
File "/home/observe_and_report/multicast_publisher.py", line 48, in publish_start
self.publish("start", message)
File "/home/observe_and_report/multicast_publisher.py", line 35, in publish
self.connect()
File "/home/observe_and_report/multicast_publisher.py", line 30, in connect
self.sock = socket.socket(sock.AF_INET, socket.SOCK_DGRAM)
答案 0 :(得分:0)
这可能不是您正在寻找的答案,但您的错误在其他地方,而不是您向我们展示的代码中。我只是把你给的东西拿到最低限度,一切正常。
import socket
class AbstractFoo:
pass
class Foo(AbstractFoo):
def __init__(self, p_id):
self.sock = 1
self.p_id = p_id
def connect(self):
ttl = 2
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
print 'self.sock =', self.sock
self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl)
def main():
f = Foo(123)
f.connect()
if __name__ == '__main__':
main()
输出:
self.sock = <socket._socketobject object at 0x10f4b91a0>
你应该从@PabloDíazOgni那里得到一个提示:问题在于:sock.AF_INET
,这是你没有向我们展示的代码。