2017-10-09 112 views
0

我是python新手。我面臨一個問題。當我在類中添加新方法時,我無法通過它們的實例變量調用它。這是問題的細節。我正在使用https://github.com/instagrambot/instabot無法從python類訪問新方法

我在bot.py文件(https://github.com/instagrambot/instabot/blob/master/instabot/bot/bot.py)中添加了新的方法。這裏是新功能的代碼。

...... 
...... 

from .bot_stats import get_user_stats_dict 

class Bot(API): 
.... 
    def get_user_stats_dict(self, username, path=""): 
     return get_user_stats_dict(self, username, path=path) 

它調用與bot_stats文件相同的名稱(文件鏈接:https://github.com/instagrambot/instabot/blob/master/instabot/bot/bot_stats.py)的新功能。這裏是我在這個文件中添加的功能代碼。

def get_user_stats_dict(self, username, path=""): 
    if not username: 
     username = self.username 
    user_id = self.convert_to_user_id(username) 
    infodict = self.get_user_info(user_id) 
    if infodict: 
     data_to_save = { 
      "date": str(datetime.datetime.now().replace(microsecond=0)), 
      "followers": int(infodict["follower_count"]), 
      "following": int(infodict["following_count"]), 
      "medias": int(infodict["media_count"]), 
      "user_id": user_id 
     } 
     return data_to_save 
    return False 

我創建了一個運行此新方法的新文件test.py。這裏是代碼腳本:

import os 
import sys 
import time 
import argparse 

sys.path.append(os.path.join(sys.path[0], '../')) 
from instabot import Bot 

bot = Bot() 
bot.login(username='username', password='pass') 
resdict = bot.get_user_stats_dict('username') 

我在CMD中使用以下命令運行test.py文件。

python test.py 

我收到以下錯誤:

AttributeError: 'Bot' object has no attribute 'get_user_stats_dict' 
+1

您是否從同一個文件導入Bot?我的意思是,你確定在不同的文件中沒有兩個Bot的定義嗎? – hspandher

+0

您正在使用該名稱從'.bot_stats import get_user_stats_dict'導入函數。爲什麼?順便說一句 - 如果這是一個實例方法,你不能簡單地導入。 – Vinny

+0

@hspandher。我已經確認了這一點。是的,它是同一個文件。我正在使用與存儲庫中相同的目錄結構。 –

回答

1

確保你有你的類內部定義一個實例方法。你得到的錯誤是因爲你的實例對象沒有這個名字的有界方法。這意味着它沒有在課堂上定義的方法,所以我會仔細檢查。 (def indent是正確的;它的位置是正確的,等等)

我試過了下面這個簡單的例子。此代碼的工作原理:

# test2.py 
def other_module_func(self): 
    print self.x 

# test.py 
from test2 import other_module_func 

class A(object): 
    def __init__(self, x): 
     self.x = x 

    def other_module_func(self): 
     return other_module_func(self) 

a = A(4) 
a.other_module_func() 
4 
+0

我對Python很新。如果你看到這個文件(https://github.com/instagrambot/instabot/blob/master/instabot/bot/bot.py)。有save_user_stats函數。我以同樣的方式添加了我的功能。 –

+0

我明白了。我已經用一個簡單的例子更新了我的答案,它在哪裏工作 – Vinny

+0

我可以通過他們的實例看到類的路徑位置嗎?就像你的例子一樣。 A類使用變量的路徑位置? –