Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Python class not recognizing static variable

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

import numpy

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

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

When the code runs though it says that it cannot make the array pop because popSize is not defined

like image 313
Nick Gilbert Avatar asked Nov 14 '13 18:11

Nick Gilbert


People also ask

Does Python class have static variables?

When we declare a variable inside a class but outside any method, it is called as class or static variable in python. Class or static variable can be referred through a class but not directly through an instance.

How do you access a static variable in Python?

If the method is an instance method, then we can access the static variable by using the self variable and class name. To access the static variable inside the class method, then we have to use @classmethod decorator and then by using the cls variable or by using classname.

How do you declare a static method in Python?

To declare a static method, use this idiom: class C: @staticmethod def f(arg1, arg2, ...): ... The @staticmethod form is a function decorator – see the description of function definitions in Function definitions for details. It can be called either on the class (such as C.f() ) or on an instance (such as C().


1 Answers

You either need to access it with a self.popSize or SimpleString.popSize. When you declare a variable in a class in order for any of the instance functions to access that variable you will need to use self or the class name(in this case SimpleString) otherwise it will treat any variable in the function to be a local variable to that function.

The difference between self and SimpleString is that with self any changes you make to popSize will only be reflected within the scope of your instance, if you create another instance of SimpleString popSize will still be 1000. If you use SimpleString.popSize then any change you make to that variable will be propagated to any instance of that class.

import numpy

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

    def __init__(self):
        pop = numpy.empty(self.popSize, object)
        target = getTarget()
        targetSize = len(target)
like image 161
jramirez Avatar answered Sep 25 '22 06:09

jramirez