python function as class attribute - AttributeError: object has no attribute

python function as class attribute - AttributeError: object has no attribute

我有 python 模块 'test.p' 和函数 'threads' 接受函数 'ping' 作为参数,它按预期工作

def ping(ip):
    print "ping", ip

def port(ip):
    print "port", ip

def threads(conn, ip):
    conn(ip)

ping('address')
threads(ping, 'address')

给我 ping('address') 的输出与 threads(ping, 'address') 相同

python test.py

ping address

ping address

现在我需要将函数 'threads' 替换为 class 'Threads' 并将函数 'ping' 用作 class 属性,这不起作用

def ping(ip):
    print "ping", ip

def port(ip):
    print "port", ip

class Threads():
    def __init__(self, func, addr):
        self.conn = func
        self.ip = addr

    def popqueue(self):
        print "popqueue"

    def dequeue(self):
        self.popqueue()
        self.conn(self.ip)

    def start(self):
        self.dequeue()


ping('address')

threads = Threads(ping, 'address')
threads.start()

这给出了以下错误:

python rep2.py

Traceback (most recent call last):
File "rep2.py", line 78, in threads.start()
File "rep2.py", line 42, in start self.dequeue()
File "rep2.py", line 39, in dequeue self.conn()

AttributeError: 'Threads' object has no attribute 'conn'

我该如何正确操作?

贴出的代码没有问题。工作正常。

请注意,与您所写的相反,您设置了 instance 属性,而不是 class 属性。

使用 python 2.7.8,您的代码似乎可以正常工作。它给了我这个输出

ping address
popqueue
ping address