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

2024-05-14 11:08:52 发布

您现在位置: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__方法,但也没有效果

谁能告诉我哪里出了问题


Tags: 方法inselfurlifheredefarguments
3条回答

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

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

此外,您不需要在变量后面添加;

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

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

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)查询current类,这将允许子类重写属性,但忽略实例属性:

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

相关问题 更多 >

    热门问题