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
You either need to access it with a
self.popSize
orSimpleString.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 useself
or the class name(in this caseSimpleString
) otherwise it will treat any variable in the function to be a local variable to that function.The difference between
self
andSimpleString
is that withself
any changes you make topopSize
will only be reflected within the scope of your instance, if you create another instance ofSimpleString
popSize
will still be1000
. If you useSimpleString.popSize
then any change you make to that variable will be propagated to any instance of that class.You need to use
self
or the class object to access class attributes:or
The latter form is really only needed if you want to bypass an instance attribute with the same name:
Here
self.bar
is an instance attribute (setting always happens on the object directly). But because there is nobaz
instance attribute,self.baz
finds the class attribute instead.