全局变量Python类

nob*_*ody 32 python global-variables

在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()
Run Code Online (Sandbox Code Playgroud)

Anu*_*yal 74

你有什么是正确的,虽然你不会把它称为全局,它是一个类属性,可以通过类访问,例如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 
Run Code Online (Sandbox Code Playgroud)

输出:

1 1 1 2 3 2
Run Code Online (Sandbox Code Playgroud)

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