简体   繁体   中英

set attribute value of class object from result of database query

I want to set attribute value for object of class in python from query database, but I get this error :

Traceback (most recent call last):
File "D:/s2/semester 3/tesis/phyton/connectDatabase", line 27, in <module>
data.append(Spatial_object(row[i]))
TypeError: __init__() takes exactly 4 arguments (2 given)

This is my code:

class Spatial_object:
    def __init__(self, jenis,Lat,Long):
        self.jenis=jenis
        self.Lat=Lat
        self.Long=Long

cur.execute("""SELECT primary_descript,lat,long from data_crime""")
row = cur.fetchall() 

data = []
for i in range(0,rows_effected):
    data.append(Spatial_object(row[i]))

Python tells exactly what the problem is - the Spatial_object.__init__() method expects three explicit arguments: jenis , Lat and Lon , while you supply only one in Spastial_object(row[i]) . Try destructing the row into a list of arguments, ie: Spatial_object(*row[i]) .

Assuming that primary_descript maps to jenis then you need to pass that and the lat and long that you retrieve from the database (once that part of your code is working juga :)) when instantiating the Spatial_object object.

This is because the __init__() method of class Spatial_object requires 4 arguments: self , jenis , Lat , and Long to match the declaration:

def __init__(self, jenis,Lat,Long):

self , which is a reference to the instance of the object itself, is passed automatically.

The second part of your code doesn't look like it will work, eg what is rows_effected ? Anyway, you don't need to know how many rows were returned, you can iterate over the rows with something like this:

cur.execute("""SELECT primary_descript,lat,long from data_crime""")

data = []
for jenis, lat, lon in cur.fetchall():
    data.append(Spatial_object(jenis, lat, lon))

You could even simplify the code further with a list comprehension:

data = [Spatial_object(jenis, lat, lon) for jenis, lat, lon in cur.fetchall()]

or a less readable version:

data = [Spatial_object(*row) for row in cur.fetchall()]

Finally, your class would be better named Spatial than Spatial_object .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM