无法从python类访问新方法
我是python新手。我面临一个问题。当我在类中添加新方法时,我无法通过它们的实例变量调用它。以下是问题的细节 我正在使用 我在bot.py文件()中添加了新方法。下面是新函数的代码无法从python类访问新方法,python,Python,我是python新手。我面临一个问题。当我在类中添加新方法时,我无法通过它们的实例变量调用它。以下是问题的细节 我正在使用 我在bot.py文件()中添加了新方法。下面是新函数的代码 ...... ...... from .bot_stats import get_user_stats_dict class Bot(API): .... def get_user_stats_dict(self, username, path=""): return get_user_
......
......
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文件(文件链接:)调用同名的新函数。这是我在这个文件中添加的函数代码
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'
确保在类中定义了一个实例方法。您得到的错误是因为您的实例对象没有该名称中的有界方法。这意味着它在类中没有定义任何方法,所以我会仔细检查一下。(def缩进正确;其位置正确,等等) 我试过下面这个简单的例子。此代码适用于:
# 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
是否从同一文件导入Bot?我的意思是,您确定不同文件中没有两个Bot定义吗?您正在从.Bot\u stats import get\u user\u stats\u dict导入一个同名函数。为什么?顺便说一句,如果这是一个实例方法,你不能简单地导入它。@hspandher。我已经确定了这一点。是的,它是同一个文件。我使用的目录结构与存储库中相同。@Vinny。它不是实例方法。我已经在一个单独的文件中定义了它,并将其导入到类文件中,以便可以从类中调用它。您需要在类中定义它,以便可以在类对象上调用它。你不能在类外导入函数并像使用实例方法一样使用它们。如果您看到此文件()。有save_user_stats函数。我以同样的方式添加了我的函数。我理解。我用一个简单的例子更新了我的答案,在这个例子中,我可以通过它们的实例看到类的路径位置。就像你的例子一样。使用变量的类的路径位置?可以将它们放在同一文件夹中吗?如果没有,你可以使用一个丑陋的黑客:将文件夹插入
sys.path
中的第一个项目。谢谢@Vinny,我安装了一个instabot软件包,现在已经删除了,它开始工作了。