Python 3.x “错误”;名称错误:名称';自我';“未定义”;即使我声明;“自我”;

Python 3.x “错误”;名称错误:名称';自我';“未定义”;即使我声明;“自我”;,python-3.x,function,class,Python 3.x,Function,Class,我正在用Python从头开始编写AdaBoost。你能详细说明一下为什么self.functions[0]=f_0这一行会导致错误吗 class AdaBoost_regressor(): def __init__(self, n_estimators, functions): # n_estimators is the number of weak regressors self.n_estimators = n_estimators

我正在用Python从头开始编写AdaBoost。你能详细说明一下为什么self.functions[0]=f_0这一行会导致错误吗

class AdaBoost_regressor():
    def __init__(self, n_estimators, functions):
        # n_estimators is the number of weak regressors     
        self.n_estimators = n_estimators
        
        # We will store the sequence of functions in object "functions"
        self.functions = np.array([None] * n_estimators, dtype = 'f')
    
    # We set f_0 = 0
    def f_0(x):
        return 0
    self.functions[0] = f_0

结果是
NameError:name'self'没有定义

我认为您出错的原因是您不能在方法之外的类内部使用
self
,因为为了使用
self
必须将类的实例作为参数传递给某个函数


请注意,在初始化类之前,表达式
self

没有任何意义。实际上,当self在外部时,它将作为变量读取。如果您声明:

self = 0
self.functions[0] = f_0
错误已消失,但“self”将被视为变量,不建议声明它。这与设置以下代码相同:

my = 0
my.functions[0] = f_0

如果删除“my=0”,它将再次抛出错误。

该类范围中没有定义任何
self
。您已将
self
定义为
\uuuu init\uuuu
方法的参数,但参数是局部变量,无法在函数外部访问。那应该在
\uuuu init\uuuu
里面吗?