简体   繁体   English

全局变量Python类

[英]Global variable Python classes

What is the proper way to define a global variable that has class scope in python? 在python中定义具有类范围的全局变量的正确方法是什么?

Coming from a C/C++/Java background I assume that this is correct: 来自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()

What you have is correct, though you will not call it global, it is a class attribute and can be accessed via class eg Shape.lolwut or via an instance eg shape.lolwut but be careful while setting it as it will set an instance level attribute not class attribute 你有什么是正确的,虽然你不会把它称为全局,它是一个类属性,可以通过类访问,例如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 

output: 输出:

1 1 1 2 3 2

Somebody may expect output to be 1 1 2 2 3 3 but it would be incorrect 有人可能期望输出为1 1 2 2 3 3但这是不正确的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM