NameError: name 'self' is not defined


最近开发Python包,遇到一个“NameError: name ‘self’ is not defined”问题。
在执行

class Tasdfa:
    
    def __init__(self,prompt='asdfa',newline=False):
        self.newline=newline
        self.prompt=prompt
        
    def __getattr__(self,prompt=self.prompt,newline=self.newline):
        if self.newline:
            print('')
        print(self.prompt)

的时候,总在“def __getattr__(self,prompt=self.prompt,newline=self.newline):”处报错:

NameError: name 'self' is not defined

错误原因是不能在类成员函数的参数里带self

self是占位用的变量。调用一个类实例的成员函数时,解释器会在实参表前添加一个传给成员函数的变量,这个变量就是类实例本身。
有时,成员函数需要对本身(即自己这个类实例)操作,所以在形参表的第一项用self占位(所以其实可以用任何的变量名,完全可以用诸如this等等)。
但是,在形参表上下文中self还没有定义:形参表的self是形参还不能被调用,必须等到成员函数内部,self指向了一个实参之后,才可以使用self的方法。

改成

class Tasdfa:
    
    def __init__(self,prompt='asdfa',newline=False):
        self.newline=newline
        self.prompt=prompt
        
    def __getattr__(self):
        if self.newline:
            print('')
        print(self.prompt)

后,正确运行。

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐