Should I be using “global” or “self.” for class scope variables in Python?

后端 未结 3 1229
礼貌的吻别
礼貌的吻别 2020-12-10 02:06

Both of these blocks of code work. Is there a \"right\" way to do this?

class Stuff:
    def __init__(self, x = 0):
        global globx
        globx = x
          


        
3条回答
  •  没有蜡笔的小新
    2020-12-10 02:22

    There are 2 ways for "class scope variables". One is to use self, this is called instance variable, each instance of a class has its own copy of instance variables; another one is to define variables in the class definition, this could be achieved by:

    class Stuff:
      globx = 0
      def __init__(self, x = 0):
        Stuff.globx = x 
      ...
    

    This is called class attribute, which could be accessed directly by Stuff.globx, and owned by the class, not the instances of the class, just like the static variables in Java.

    you should never use global statement for a "class scope variable", because it is not. A variable declared as global is in the global scope, e.g. the namespace of the module in which the class is defined.

    namespace and related concept is introduced in the Python tutorial here.

提交回复
热议问题