pythonpython-2.7web2pyweb2py-modules

How to make user defined classes in web2py


I am trying to make a class within a module, import that module file in my controller, and then reference the class that is defined within that module, but I keep getting a message that reads NameError("name 'self' is not defined")

Here is my code in my created module:

from gluon import *

class device_info(object):

    self.info = {}

    def __init__(self, info):
        self.info = info
        return
    def setInfo(info):
        self.info = info
        return
    def getInfo():
        return self.info`

Does anyone know what causes this and how it can be resolved? I was under the impression that user-defined classes were supported in web2py.


Solution

  • As stated, just move self.info = {} into __init__().

    __init__() is essentially a constructor that you are familiar with from java. It initializes an instance object of that class when called. I haven't used Java in some time, but I don't think you should be be declaring class variables outside of your constructor there either.

    self is an argument that all methods within a class in python must receive as their first argument. So your getters and setters are also not going to work if you try them; they must be:

    def setInfo(self, info) and def getInfo(self)

    When you create an object, like this:

    device1 = device_info()

    it calls __init()__, passing device1 as self. Then, whenever you use that object, such as

    device1.setInfo(newInfo), you can think of the method in the class' context being called as setInfo(device1, newInfo), since device1 is self, or the current instance of the device_info object in use.

    You also don't need the object argument at the class definition. What do you expect that to do?


    Edit: Actually, don't move self.info = {} into __init__(), just get rid of it. You already have self.info = info in __init__(). You don't need to initialize variables like that in Python like you do in Java. Creating an empty dict and then setting it to another dict without any use is redundant.