Python3,在另一个类中使用对象实例

Python3,在另一个类中使用对象实例,python,python-3.x,instance-variables,Python,Python 3.x,Instance Variables,我试图通过引用\uuuu init\uuuu方法中的对象来修改class属性,然后在另一个方法中使用它。遗憾的是,下面的代码示例没有按预期工作 代码 class Translator: #list of attributes parser=None def __init__(self): parser = Parser_class() ... #some other commands def Translate(self)

我试图通过引用
\uuuu init\uuuu
方法中的对象来修改class属性,然后在另一个方法中使用它。遗憾的是,下面的代码示例没有按预期工作

代码

class Translator:
    #list of attributes
    parser=None
    def __init__(self):   
         parser = Parser_class() ...
         #some other commands
    def Translate(self): 
         something=self.parser.GenerateHead() ...
         #more commands
编译错误

AttributeError: 'NoneType' object has no attribute 'GenerateHead'

我知道我可以将它作为参数提供给
Translate
方法,我只是好奇为什么Python中的这条语句不起作用。

您的实例属性做得不对

首先,您不需要提前声明属性。将
parser=None
放在类的顶层会创建一个名为
parser
的类变量,我认为这不是您想要的。通常在Python中,您可以通过一个简单的赋值随时添加新的实例属性:
instance.attr=“whatever”

第二,当您想从方法中分配实例时,您需要使用
self
来引用实例。如果您关闭了
self
,您将分配给函数中的局部变量,而不是实例或类变量。实际上,没有必要使用特定的名称
self
,但是您确实需要使用该方法的第一个参数(打破命名该
self
的惯例可能不是一个好主意)

因此,要修复代码,请执行以下操作:

class Translator:
    # don't declare variables at class level (unless you actually want class variables)

    def __init__(self):   
         self.parser = Parser_class()   # use self to assign an instance attribute

    def Translate(self): 
         something = self.parser.GenerateHead()  # this should now work