0

I'm trying to connect to a sqllite database using:

class Sqllite_utilities(object):

    def __init__(self):

        parser = argparse.ArgumentParser()
        parser.add_argument("-s","--source", type=str,
                            help="source table from db")
        args = parser.parse_args()
        print(args)


        source_table= args.source

        db_path = "sqlite:///"+settings.SETTINGS_PATH+"\\data.db"

        dataset_db = dataset.connect(db_path)
        self.dataset_table = dataset_db[source_table]


    def missing_ids(self):

        for user in self.dataset_table:
            print(user['id'])


if __name__ == '__main__':
    Sqllite_utilities.missing_ids(sys.argv[1])

When I do:

$ python find_missing_records.py -s test

I get:

Traceback (most recent call last):
  File "find_missing_records.py", line 41, in <module>
    Sqllite_utilities.missing_ids(sys.argv[1])
TypeError: unbound method missing_ids() must be called with Sqllite_utilities instance as first argument (got str instance instead)
(contact2E)

What am I doing wrong?

user1592380
  • 34,265
  • 92
  • 284
  • 515

2 Answers2

4

When doing:

Sqllite_utilities.missing_ids(sys.argv[1])

you're calling the missing_ids instance method with sys.argv[1] (a string) as self (functional way to call instance methods, but with the wrong object), which explains the error message.

It's clear that you have to create an instance of your object before being able to use the instance methods (the ones without @staticmethod or @classmethod decorators):

if __name__ == '__main__':
    s = Sqllite_utilities()

the constructor parses the arguments, using argparse.ArgumentParser which uses sys.argv by default, so leave that aside, it'll work.

Then call your method on the instance:

s.missing_ids()

s is implicitly passed as self when calling missing_ids

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
  • Thank you that works. With regard to "It's clear that you have to create an instance of your object before being able to use the instance methods (the ones without staticmethod or classmethod decorators)", are you saying that class and static methods do not need the class to be instantiated first, but other methods do? – user1592380 Mar 14 '17 at 20:57
  • yes, you can use class/static methods without any instance. – Jean-François Fabre Mar 14 '17 at 20:59
  • Thank you, that helps my understanding. – user1592380 Mar 14 '17 at 21:02
1

As suggested from the top answer to this question: unbound method f() must be called with fibo_ instance as first argument (got classobj instance instead)

Add to your code:

if __name__ == '__main__':
    obj = Sqllite_utilities()
    s.missing_ids()
Community
  • 1
  • 1
John Moutafis
  • 22,254
  • 11
  • 68
  • 112