Search code examples
pythonclassoopattributesself

global name self not defined in inherited class


I have defined an abstract base class in python:

class calculator:
    __metaclass__ = ABCMeta

    @abstractmethod
    def __init__(self, fileName):
        path = './cartesians/'
        onlyFiles = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))]
        for elem in list(onlyFiles):
            test = elem.split('.')[0]
            if test != fileName.split('.')[0]:
                onlyFiles.remove(elem)
        self.onlyFiles = onlyFiles
        self.onlyFiles.sort()

    @abstractmethod
    def optimize(self):
        pass

mopac class is inherited from calculator class:

from calculator import *

class mopac(calculator):

     def __init__(self, fileName):
        self.test = "test"
        super(mopac, self).__init__(fileName)

    def optimize(calculator):
        print self.test
        for file in self.onlyFiles:
           do stuff

and in main.py, I have:

from mopac import *

calc = mopac(inFile)
calc.optimize()

when I run the code, it tells me:

File "main.py", line 50, in main
    calc.optimize()
  File "path/mopac.py", line 24, in optimize
    print self.test
NameError: global name 'self' is not defined

I don't understand why it's treating self as a variable/attribute here. Could someone help please? If I remove "print self.test", then it gives me the same error "self is not defined" with self.onlyFiles.


Solution

  •   def optimize(calculator):
            print calculator.test
            for file in calculator.onlyFiles:
               do stuff
    

    The first argument of every class method, including init, is always a reference to the current instance of the class. By convention, this argument is always named self. In the init method, self refers to the newly created object; in other class methods, it refers to the instance whose method was called.

    In this case your are renaming the 'self' variable to 'calculator'. Either change it to self or rename self to calculator.

    More info

    Other that may help you