python遇到動態函數---TypeError: unbound method a() must be called with A instance as first argument (got nothing instead)


TypeError: unbound method a() must be called with A instance as first argument (got nothing instead)

# encoding: utf-8

import time
import threading

class test:

    def follow(self,thefile):
        thefile.seek(0,2)
        while True:
            line = thefile.readline()
            if not line:
                time.sleep(0.1)
                continue
                yield line

if __name__ == '__main__':

    # obj = test()
    file1 = 'log.txt'
    file2 = 'result.txt'
    logfile = open(file2,"r")
    # loglines = obj.follow(logfile)
    loglines = test.follow(logfile)
    for line in loglines:
        print line,

運行結果

C:\Python27\python.exe C:/Users/sys_syspifarm/.ssh/MagicBox/source/test.py
Traceback (most recent call last):
File "C:/Users/sys_syspifarm/.ssh/MagicBox/source/test.py", line 44, in <module>
loglines = test.follow(logfile)
TypeError: unbound method follow() must be called with test instance as first argument (got file instance instead)

Process finished with exit code 1

錯誤原因:函數a()非靜態方法,故需實例化然后才能使用,改正如下:

# encoding: utf-8

import time
import threading

class test:

    def follow(self,thefile):
        thefile.seek(0,2)
        while True:
            line = thefile.readline()
            if not line:
                time.sleep(0.1)
                continue
                yield line

if __name__ == '__main__':

    obj = test()
    file1 = 'log.txt'
    file2 = 'result.txt'
    logfile = open(file2,"r")
    loglines = obj.follow(logfile)
    # loglines = test.follow(logfile)
    for line in loglines:
        print line,

obj = test()需要把方法實例化一下


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM