我在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): passmopac类是从计算器类继承的:
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并在main.py中,我有:
from mopac import * calc = mopac(inFile) calc.optimize()当我运行代码时,它告诉我:
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我不明白为什么这里把自己当作变量/属性来对待。 有人可以帮忙吗? 如果我删除“print self.test”,那么它会给我提供与self.onlyFiles相同的错误“self is not defined”。
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): passmopac 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 stuffand 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 definedI 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.
最满意答案
def optimize(calculator): print calculator.test for file in calculator.onlyFiles: do stuff每个类方法(包括init)的第一个参数始终是对当前类实例的引用。 按照惯例,这个参数总是被命名为self。 在init方法中,self指新创建的对象; 在其他类方法中,它指的是其方法被调用的实例。
在这种情况下,您将“自我”变量重命名为“计算器”。 将其改为自我或将自己重命名为计算器。
更多信息
其他可能会帮助你
def optimize(calculator): print calculator.test for file in calculator.onlyFiles: do stuffThe 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
更多推荐
发布评论