Python:在同一个类的方法中使用变量

时间:2015-12-01 14:00:40

标签: python

我一直在做一些研究,但到目前为止,我没有发现完全复制我的问题。

这是我正在尝试做的事情:

class FilterClass:
    ALPHABETIC = "a";
    NUMERIC = "n"
    URL = "u";
    def textRestriction(self, text, arguments):
        if ALPHABETIC in arguments:
            #do crap here
        if NUMERIC in arguments:
            #do other crap here

我在班级FilterClass中创建了变量。它们将在类之外使用,以及类本身中的方法,但它们永远不会被修改。

我遇到了global name 'ALPHABETIC' is not defined错误,并在方法中添加变量并向其添加全局变量。我也尝试添加__init__方法,但它也没有做任何事情。

谁能告诉我哪里出错?

3 个答案:

答案 0 :(得分:2)

您已经创建了类变量,因此您只需要添加类名,如下所示:

class FilterClass:
    ALPHABETIC = "a"
    NUMERIC = "n"
    URL = "u"

    def textRestriction(self, text, arguments):
        if FilterClass.ALPHABETIC in arguments:
            print 'Found alphabetic'
        if FilterClass.NUMERIC in arguments:
            print 'Found numeric'

fc = FilterClass()
fc.textRestriction('test', 'abc n')

这会显示:

Found alphabetic
Found numeric

此外,您无需在变量后添加;

答案 1 :(得分:1)

python中的实例属性需要引用为self.identifier,而不仅仅是identifier。 python中的类属性可以引用为self.identifierClassName.identifier

所以你的意思是:

def textRestriction(self, text, arguments):
    if FilterClass.ALPHABETIC in arguments:
        #do crap here
    if FilterClass.NUMERIC in arguments:
        #do other crap here

答案 2 :(得分:0)

您创建了类属性;你需要在课堂上引用它们:

class FilterClass:
    ALPHABETIC = "a"
    NUMERIC = "n"
    URL = "u"

    def textRestriction(self, text, arguments):
        if FilterClass.ALPHABETIC in arguments:
            #do crap here
        if FilterClass.NUMERIC in arguments:
            #do other crap here

类属性不是全局变量,类主体定义也不是类的方法所涉及的范围。

你也可以像引用实例一样引用它们;如果没有这样的实例属性,Python将自动查找类属性:

def textRestriction(self, text, arguments):
    if self.ALPHABETIC in arguments:
        #do crap here
    if self.NUMERIC in arguments:
        #do other crap here

访问这些名称的另一种方法是查询带有type(self)当前类,这将允许子类覆盖属性,但忽略实例属性:

def textRestriction(self, text, arguments):
    if type(self).ALPHABETIC in arguments:
        #do crap here
    if type(self).NUMERIC in arguments:
        #do other crap here