定义在python中具有类作用域的全局变量的正确方法是什么?

来自C/C++/Java背景,我认为这是正确的:

class Shape:
    lolwut = None

    def __init__(self, default=0):
        self.lolwut = default;
    def a(self):
        print self.lolwut
    def b(self):
        self.a()

最佳答案

您所拥有的是正确的,尽管您不会将其称为全局,但它是一个类属性,可以通过类Shape.lolwut或实例来访问。 shape.lolwut,但在设置时要小心,因为它将设置实例级别的属性而不是类的属性

class Shape(object):
    lolwut = 1

shape = Shape()

print Shape.lolwut,  # 1
print shape.lolwut,  # 1

# setting shape.lolwut would not change class attribute lolwut
# but will create it in the instance
shape.lolwut = 2

print Shape.lolwut,  # 1
print shape.lolwut,  # 2

# to change class attribute access it via class
Shape.lolwut = 3

print Shape.lolwut,  # 3
print shape.lolwut   # 2

输出:
1 1 1 2 3 2

有人可能期望输出是1 1 2 2 3 3,但它是不正确的

关于python - 全局变量Python类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6475321/

10-10 11:40