2017-10-09 6 views
0

私はPythonには初めてです。私は問題に直面している。クラスに新しいメソッドを追加すると、インスタンス変数を使って呼び出すことができません。ここに問題の詳細があります。クラスpythonから新しいメソッドにアクセスできません

私はhttps://github.com/instagrambot/instabotを使用しています。

私は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

同じファイルからボットをインポートしていますか?つまり、異なるファイルに2つのBotの定義がないことは確かですか? – hspandher

+0

その名前の関数を '.bot_stats import get_user_stats_dict'からインポートしています。どうして? btw - インスタンスメソッドの場合、単純にインポートすることはできません。 – Vinny

+0

@ hspandher。私はすでにこの点を確認しています。はい、同じファイルです。私はリポジトリと同じディレクトリ構造を使用しています。 @Vinny。 –

答えて

1

あなたはインスタンスメソッドクラス内で定義されていることを確認しますが。 インスタンスオブジェクトには、その名前に限定されたメソッドがないため、エラーが発生します。つまり、クラスにメソッドが定義されていないことを意味します。 (デプスインデントが正しい、位置が正しいなど)

私は次の簡単な例を試しました。このコードの動作:

# 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

クラスのパス位置をインスタンスで表示できますか?あなたの例のように。変数を使用してクラスのパスの場所? –

関連する問題