Ign Ign - 3 months ago 11
Python Question

Python - cannot access class property

I'm writing a class to access a mySQL db from python.

Here's the code:

#!/usr/bin/python

import MySQLdb
import configparser

class db():

def __init__(self):

try:
self.handler = MySQLdb.connect(host="localhost", user=user, passwd=passwd, db=dbname)
self.cur = self.handler.cursor()
except:
print "Couldn't connect to db"


def query(self, query):

self.lastQuery = query
self.res = self.cur.execute(query)

def close(self):

self.handler.close()


When I'm trying to call the class, it give me the following error:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "db.class.py", line 6, in <module>
class db():
File "db.class.py", line 25, in db
self.res = self.cur.execute(query)
NameError: name 'self' is not defined


I've been searching and commonly there's people that forget to define the method with 'self' as an argument. But I'm including it.

Could anyone help me?

Thanks.

UPDATE:

I checked whitespaces and tabs and that is not the problem.

Answer

Your code has mixed tabs and spaces, causing Python to get confused about what statements are at what indentation level. The assignment to self.res has ended up at class level, outside of the method it was intended to be a part of.

Stop mixing tabs and spaces. Turn on "show whitespace" in your editor to make the problem more visible, and consider running Python with the -tt flag to give an error on ambiguous mixing of tabs and spaces.