本文介绍了为什么Python类不能识别静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

当代码运行时,它说它不能使数组pop,因为popSize没有定义

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

推荐答案

您需要使用 self.popSize SimpleString.popSize 来访问它。当你在类中声明一个变量以便任何实例函数访问该变量时,你需要使用 self 或类名(在这种情况下 SimpleString )否则会将函数中的任何变量视为该函数的局部变量。

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.

self SimpleString 之间的区别是 self 您对 popSize 所做的任何更改只会反映在您的实例范围内,如果您创建另一个实例 SimpleString popSize 将仍然是 1000 。如果使用 SimpleString.popSize ,那么对该变量所做的任何更改都将传播到该类的任何实例。

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)

这篇关于为什么Python类不能识别静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 08:04