在Python类中定义常量,self真的必要吗?

31 投票
5 回答
57816 浏览
提问于 2025-04-16 05:54

我想在一个类里面定义一组常量,像这样:

class Foo(object):
   (NONEXISTING,VAGUE,CONFIRMED) = (0,1,2)
   def __init__(self):
       self.status = VAGUE

但是,我遇到了这个问题:

NameError: global name 'VAGUE' is not defined

有没有办法在类里面定义这些常量,让它们可见,而不需要使用 global 或者 self.NONEXISTING = 0 这种方式呢?

相关问题:

5 个回答

4

这个方法绝对不推荐在任何代码中使用,但下面这种丑陋的黑客方式是可以做到的。我这样做只是为了更好地理解Python的AST API,所以任何在实际代码中使用这个方法的人都应该被制止,以免造成伤害 :-)

#!/usr/bin/python
# -*- coding: utf-8-unix -*-
#
# AST hack to replace symbol reference in instance methods,
# so it will be resolved as a reference to class variables.
#

import inspect, types, ast

def trim(src):
    lines = src.split("\n")
    start = lines[0].lstrip()
    n = lines[0].index(start)
    src = "\n".join([line[n:] for line in lines])
    return src

#
# Method decorator that replaces symbol reference in a method
# so it will use symbols in belonging class instead of the one
# in global namespace.
#
def nsinclude(*args):
    # usecase: @nsinclude()
    # use classname in calling frame as a fallback
    stack = inspect.stack()
    opts  = [stack[1][3]]

    def wrap(func):
        if func.func_name == "tempfunc":
            return func

        def invoke(*args, **kw):
            base = eval(opts[0])

            src = trim(inspect.getsource(func))
            basenode = ast.parse(src)

            class hackfunc(ast.NodeTransformer):
                def visit_Name(self, node):
                    try:
                        # if base class (set in @nsinclude) can resolve
                        # given name, modify AST node to use that instead
                        val = getattr(base, node.id)

                        newnode = ast.parse("%s.%s" % (opts[0], node.id))
                        newnode = next(ast.iter_child_nodes(newnode))
                        newnode = next(ast.iter_child_nodes(newnode))
                        ast.copy_location(newnode, node)
                        return ast.fix_missing_locations(newnode)
                    except:
                        return node

            class hackcode(ast.NodeVisitor):
                def visit_FunctionDef(self, node):
                    if func.func_name != "tempfunc":
                        node.name = "tempfunc"
                        hackfunc().visit(node)

            hackcode().visit(basenode)

            newmod = compile(basenode, '<ast>', 'exec')
            eval(newmod)
            newfunc = eval("tempfunc")
            newfunc(*args, **kw)
        return invoke


    # usecase: @nsinclude
    if args and isinstance(args[0], types.FunctionType):
        return wrap(args[0])

    # usecase: @nsinclude("someclass")
    if args and args[0]:
        opts[0] = args[0]
    return wrap

class Bar:
    FOO = 987
    BAR = 876

class Foo:
    FOO = 123
    BAR = 234

    # import from belonging class
    @nsinclude
    def dump1(self, *args):
        print("dump1: FOO = " + str(FOO))


    # import from specified class (Bar)
    @nsinclude("Bar")
    def dump2(self, *args):
        print("dump2: BAR = " + str(BAR))

Foo().dump1()
Foo().dump2()
11

试试用这个代替:

self.status = VAGUE

这个:

self.status = Foo.VAGUE

你必须指定类

39

当你在类的主体中给名字赋值时,其实是在创建这个类的属性。你不能直接使用这些属性,必须通过类来引用它们,可以直接用 Foo.VAGUE,也可以用 self.VAGUE。不过,你不需要给 self 的属性重新赋值。

通常情况下,使用 self.VAGUE 是比较合适的,因为这样可以让子类重新定义这个属性,而不需要重新实现所有使用这个属性的方法。虽然在这个例子中这样做似乎不太合理,但谁知道呢。

撰写回答