2014-10-08 94 views
-1

在我開始之前還有很多其他確切的問題,但是沒有一個答案足以解決我的問題。類/功能log.info('foo')沒有問題,運行一次,但是它把它稱爲第二次得到的錯誤TypeError: 'str' object is not callableTypeError:'str'對象不可調用。即使沒有什麼叫'str'

我發現this question有同樣的問題我,但我沒有什麼所謂的海峽。我已經與其他功能進行過測試,即戰爭。

我的代碼:

import praw 
import sys 
import traceback 
from accounts import * 

class logging: 

    def info(self, log): 
     self.info = '\033[94m' 
     self.rs = '\033[0m' 
     print self.info, 'INFO: ', self.rs 

    def warn(self, log): 
     self.warn = '\033[93m' 
     self.rs = '\033[0m' 
     print self.warn, 'WARNING: ', self.log, self.rs 

    def critical(self, log): 
     self.critical = '\033[91m' 
     self.rs = '\033[0m' 
     print self.critical, 'CRITICAL: ', log, self.rs 

def read_accounts(): 
    with open('accounts.py') as f: 
     for i, l in enumerate(f): 
      pass 

    i += 1 
    accounts = {} 

    while i > 0: 
     ac = globals()['account_%s' %i] 
     index = ac.find(':') 
     uname = ac[0:index] 
     password = ac[index+1:len(ac)] 
     accounts[uname] = password 
     i -= 1 

    log.info('Usernames loaded successfully! Usernames loaded:') 
    print accounts 

def main(): 
    log.info('Initilizing reddit accounts from file...') 
    try: 
     read_accounts() 
    except: 
     traceback.print_exc() 
     log.critical('Can not read accounts! Make sure format is correct!') 
     sys.exit() 


if __name__ == '__main__': 
    log = logging() 
    main() 

而且我知道在Python記錄模塊,但我想我自己做的事!

在此先感謝!

+0

您的'accounts'模塊中是否有名爲'log'的模塊級變量? – nofinator 2014-10-08 17:55:31

回答

4

的問題是,你logging類重新定義了它的所有實例方法爲字符串:

class logging: 

    def info(self, log): 
     self.info = '\033[94m' # self.info is not a function anymore 
     self.rs = '\033[0m' 
     print self.info, 'INFO: ', self.rs 

所以你第一次叫log.info,它調用info功能。第二次,它嘗試調用字符串'\033[94m'

只需在所有方法中爲該實例變量使用不同的名稱 - 或者根本不要使其成爲實例變量。無論如何,每次調用方法時都重新定義它:

class logging: 

    def info(self, log): 
     info_prefix = '\033[94m' # no conflict 
     self.rs = '\033[0m' 
     print info_prefix, 'INFO: ', self.rs 
+0

謝謝!太棒了! – George 2014-10-08 18:19:11

相關問題