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

时间:2013-11-14 18:43:59

标签: python class oop variables static

我正在尝试使用静态变量和方法(属性和行为)在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未定义

2 个答案:

答案 0 :(得分:21)

您需要使用self.popSizeSimpleString.popSize来访问它。当您在类中声明变量以便任何实例函数访问该变量时,您将需要使用self或类名(在本例中为SimpleString),否则它将处理任何变量在函数中是该函数的局部变量。

selfSimpleString之间的区别在于selfpopSize所做的任何更改只会反映在您的实例范围内,如果您创建另一个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)

答案 1 :(得分:3)

您需要使用self或类对象来访问类属性:

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

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

如果您想绕过具有相同名称的实例属性,则实际上只需要后一种形式:

>>> class Foo(object):
...     bar = 42
...     baz = 42
...     def __init__(self):
...         self.bar = 38
...     def printBar(self):
...         print self.bar, Foo.bar
...     def printBaz(self):
...         print self.baz, Foo.baz
... 
>>> f = Foo()
>>> f.printBar()
38 42
>>> f.printBaz()
42 42

这里self.bar是一个实例属性(设置总是直接在对象上发生)。但由于没有baz实例属性,self.baz会找到类属性。