为什么Python类不能识别静态变量

Nic*_*ert 12 python oop variables static class

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

import numpy

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

    def __init__(self):
        pop = numpy.empty(popSize, object)
        target = getTarget()
        targetSize = len(target)
Run Code Online (Sandbox Code Playgroud)

代码运行虽然它说它不能使数组弹出,因为没有定义popSize

jra*_*rez 21

您需要使用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)
Run Code Online (Sandbox Code Playgroud)