私は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'
同じファイルからボットをインポートしていますか?つまり、異なるファイルに2つのBotの定義がないことは確かですか? – hspandher
その名前の関数を '.bot_stats import get_user_stats_dict'からインポートしています。どうして? btw - インスタンスメソッドの場合、単純にインポートすることはできません。 – Vinny
@ hspandher。私はすでにこの点を確認しています。はい、同じファイルです。私はリポジトリと同じディレクトリ構造を使用しています。 @Vinny。 –