Understanding the 'NoneType' Object has no attribute '__getitem__' Error in Python

Asked 2 years ago, Updated 2 years ago, 135 views

How on earth can we solve the error in the image?
As a result of the investigation, there seems to be a problem with the attributes, but I am not sure, so I asked you a question.

The source code is listed below.

Thank you for your cooperation.

import sys,getopt
import sqlite3

class Location:

    def_init__(self, filename=""):
        self.filename = filename
        self.locations=list()

    def seek (self):
        if self.filename==":
            return False

        file=open(self.filename, "r")

        For line in file:
            line_sep = line.split("\t")
            if(len(line_sep)>2):
                if(line_sep[1]=="LOC"):
                   time=line_sep[2].split(',')[0]
                   latitude=line_sep[2].split(',')[1]
                   longitude=line_sep[2].split(',')[2]

                   location={'time':time, 'latitude':latitude, 'longitude':longitude}
                   self.locations.append(location)
        return True

    def printAll(self):
        if(len(self.locations)>0):
            print'time, latitude, longitude'
        for location in self.locations:
            print location ['time'], location ['latitude'], location ['longitude']  

Class Audio:

    def_init__(self, filename=""):
        self.filename = filename
        self.startTime = 0.0
        self.stopTime = 0.0

    def seek (self):
        if self.filename==":
            return False

        file=open(self.filename, "r")

        For line in file:
            line_sep=line.split()
            if(len(line_sep)>2):
                if(line_sep[1]=="AUDIO"):
                    if(line_sep[2]=="start"):
                        self.startTime=line_sep[0]
                    elif(line_sep[2]=="stop"):
                        self.stopTime=line_sep[0]

        return True

    def printTime (self):
        print self.startTime, self.stopTime

    defaultDuration(self):
        return(float(self.stopTime)-float(self.startTime))


Class FileManager:
    def__init__(self, filename, database):
        # database connection
        self.conn=sqlite3.connect(database)
        self.cur = self.conn.cursor()
        self.filename = filename

        # filename must be separated by '-'. (e.g.hasc-20120527-115511-raw.log)
        self.idname='-'.join(filename.split("-")[0:3])

    def_getFileinfoId(self):
        self.cur.execute("select fileinfo.id from files inner join fileinfo on files.id=fileinfo.fileId where files.filename like'"+self.idname+"%')
        return self.cur.fetphone() [0]

    defaultDatabase(self):
        fileinfoId=str(self._getFileinfoId())
        audio=Audio(self.filename)
        audio.seek()

        self.cur.execute("update fileinfo set startTime='+audio.startTime+"'where id="+fileinfoId)
        self.cur.execute("update fileinfo set endTime='+audio.stopTime+"'where id="+fileinfoId)
        self.conn.commit()

        loc=Location(filename=self.filename)
        loc.seek()
        for location in loc.locations:
            self.cur.execute("insert into geolocations(fileId, time, latitude, longitude) values("+fileinfoId+", "+location['time']+", "+location['latitude']+", "+location['longitude']+")
            self.conn.commit()

defmain(argv):
    logfile='"
    database='"
    try:
        opts, args=getopt.getopt(argv, "hl:d:", ["log=", "db="])
        iflen(opts)<1:
            raise getopt.GetoptError("")
    except getopt.GetoptError:
        print 'hascseeker.py --log<logfile>--db<databasefile>'
        sys.exit()
    for opt, argin opts:
        if opt in ("-h", "--help"):
            print 'hascseeker.py --log<logfile>--db<databasefile>'
            sys.exit()
        elifopt in ("-l", "--log"):
            logfile=arg
        elifopt in ("-d", "--db"):
            database=arg

    man = FileManager (logfile, database)
    man.updateDatabase()

if__name__=="__main__":
   main(sys.argv[1:])

Error Screen

python sqlite

2022-09-30 20:32

2 Answers

If the SQL statement has zero results, fetphone() returns None.

11.13.sqlite3—DB-API 2.0 interface for SQLite databases

Cursor.fetphone()

Fetches the next row of a query result set, returning a single sequence, or None when no more data is available.

Therefore, it should be written as follows.

def_getFileinfoId(self):
  self.cur.execute("select fileinfo.id from files inner join fileinfo on files.id=fileinfo.fileId where files.filename like'"+self.idname+"%')
  result=self.cur.fetphone()
  return (None if result is None else result [0])

However, in the case of None, I will return it as it is, so please change it accordingly.


2022-09-30 20:32

If you look at heliac2001's answer, you don't seem to understand what the error means, so please understand the meaning of the error message a little.

'NoneType' object has no attribute'__getitem__'

Attribute can be translated as an attribute, but the meaning of this error is simply a method or property.

It means "(like calling _getitem__), but you don't have a method or property called _getitem__.

The first 'NoneType' object is an object of type None.The variable is (None, not letters or numbers).

To sum up (not so much),
"The line in question tries to use __getitem__ for a none-type object, but the object does not have anything called _getitem__"

This error is exactly the same as the following code.

sample=None
sample.__getitem__(0)

Now, the question arises as to where the _getitem__ that does not exist in the code came from, which is a special method Python calls internally (magic method).

When accessing container variables such as varname[0], python implicitly invokes the _getitem__ method (the magic method is usually not something that Python invokes internally, so the user can call it).

 Python 2.7.8 (default, Jun 30 2014, 16:03:49) [MSC v.1500 32-bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>a = ['x', 'y']
>>a [0]
'x'
>>>a.__getitem__(0)<-getitem can be retrieved in the same way.
'x'

>>b = {'a': 'A', 'b': 'B'}
>>b ['a']
'A'
>>>b.__getitem__('a')<-getitem can be obtained in the same way.
'A'
>>b.__getitem__('b')
'B'

_xxxx__ Imagine trying to start with a name if a style description appears in the error.

In self.cur.fetphone()[0], fetphone() returns None, so None[0] and there is an error trying to retrieve the 0th item from the None type.

I explained it, but it may not be easy to understand (^^;

)


2022-09-30 20:32

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.