Why is Python class not recognizing static variable

后端 未结 2 1636
耶瑟儿~
耶瑟儿~ 2020-12-18 23:13

I am trying to make a class in Python with static variables and methods (attributes and behaviors)

import numpy

class SimpleString():    
    popSize = 100         


        
2条回答
  •  天命终不由人
    2020-12-19 00:18

    You need to use self or the class object to access class attributes:

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

    or

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

    The latter form is really only needed if you want to bypass an instance attribute with the same name:

    >>> 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
    

    Here self.bar is an instance attribute (setting always happens on the object directly). But because there is no baz instance attribute, self.baz finds the class attribute instead.

提交回复
热议问题