为什么Python类无法识别静态变量


问题内容

我试图用静态变量和方法(属性和行为)在Python中创建一个类

import numpy

class SimpleString():    
    popSize = 1000 
    displaySize = 5
    alphatbet = "abcdefghijklmnopqrstuvwxyz "

    def __init__(self):
        pop = numpy.empty(popSize, object)
        target = getTarget()
        targetSize = len(target)

当代码运行时,虽然说它无法使数组弹出,因为未定义popSize


问题答案:

您需要使用self.popSize或访问它SimpleString.popSize。当您在类中声明变量以便任何实例函数访问该变量时,您将需要使用self该类名,SimpleString否则将使用类名(在这种情况下),否则它将将该函数中的任何变量视为该变量的局部变量功能。

之间的区别self,并SimpleString是与self任何更改您对popSize只会您的实例的范围内体现出来,如果你创建的另一个实例SimpleString
popSize仍然会1000。如果使用,SimpleString.popSize则对该变量所做的任何更改都将传播到该类的任何实例。

import numpy

class SimpleString():    
    popSize = 1000 
    displaySize = 5
    alphatbet = "abcdefghijklmnopqrstuvwxyz "

    def __init__(self):
        pop = numpy.empty(self.popSize, object)
        target = getTarget()
        targetSize = len(target)