Abdul Rauf
Abdul Rauf

Reputation: 761

unable to access new method from class python

I am new to python. I am facing a issue. When i add new method in a class, then i am unable to call it through their instance variable. Here is the details of the issue.

I am using https://github.com/instagrambot/instabot.

I have added new method in bot.py file (https://github.com/instagrambot/instabot/blob/master/instabot/bot/bot.py). Here is code of new function.

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

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)

It is calling new function with the same name from bot_stats file(file link: https://github.com/instagrambot/instabot/blob/master/instabot/bot/bot_stats.py). Here is the function code which i have added in this file.

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

I have created a new file test.py which is running this new method. Here is the code script:

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')

I am running test.py file using following command in CMD.

python test.py

I am getting following error:

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

Upvotes: 0

Views: 89

Answers (1)

Chen A.
Chen A.

Reputation: 11280

Make sure you have an instance method defined inside your class. The error you get is because your instance object has no bounded methods in that name. This means it has no method defined in the class, so I would double check that. (the def indent is correct; it's location is right, etc.)

I have tried the following simple example. This code works:

# 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

Upvotes: 1

Related Questions