user3375667
user3375667

Reputation: 25

self argument not defined when calling method?

Hi I am developing a system that is making use of the Phidget sensors and having some issues trying to write some variables to a database. I have read around a fair amount on classes and calling variables but I just cannot get this code to run.

My code is below, as you can see I have put the 'self' argument when database method is called but it is complaining 'self' is not defined. If I don't have self in there I get a complaint that 'database() missing 1 required positional argument: 'self''

connection = sqlite3.connect('testing.db')      
cursor = connection.cursor()

class sensors():

    def interfaceKitAttached(self, e):
        attached = e.device
        print("InterfaceKit %i Attached!" % (attached.getSerialNum()))

    def sensorInputs(self, e):



        temperature = (interfaceKit.getSensorValue(0)*0.2222 - 61.111)
        self.sound =  (16.801 * math.log((interfaceKit.getSensorValue(1))+ 9.872))
        light = (interfaceKit.getSensorValue(2))

        print("Temperature is: %i " % temperature)
        print("Sound is : %i" %self.sound)
        print("Light is: %i \n" %light)

        interfaceKit.setSensorChangeTrigger(0, 25)
        interfaceKit.setSensorChangeTrigger(1, 35)
        interfaceKit.setSensorChangeTrigger(2, 60)


    def database(self):


        cursor.execute('''CREATE TABLE events1
        (sensor text, value text)''')

        cursor.execute ('INSERT INTO events1 VALUES (?, ?)', ('sounding', self.sound))


        connection.commit()
        connection.close()




try:
    interfaceKit.setOnAttachHandler(interfaceKitAttached)
    interfaceKit.setOnSensorChangeHandler(sensorInputs)
    database(self)

Thanks

Upvotes: 0

Views: 1277

Answers (1)

sshashank124
sshashank124

Reputation: 32189

self is not an argument that you pass in the parenthesis. self is an argument that is passed as follows:

object.method()

Here you are actually passing the object as an argument, self.

Therefore, in your case, you actually need to call the method in the form of object.method() where object is an instance of the class that your method is in. In this case, your class is sensors.

So you do NOT do:

database(self)

you do

sensors_object = sensors()

sensors_object.database()

When you call the sensors_object = sensors() call, you create a new sensors object. Then you call the OBJECT's method NOT the CLASS's method in the line that follows.

[NOTE:] I recommend that you create a def __init__(self): method. This is the method that gets called when you create a new instance of a class. In this __init__ method, you initialize all the different variables that you need as self.variable_name = something

Upvotes: 1

Related Questions