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

后端 未结 3 1233
礼貌的吻别
礼貌的吻别 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:27

    You should use the second way, then every instance has a separate x

    If you use a global variable then you may find you get surprising results when you have more than one instance of Stuff as changing the value of one will affect all the others.

    It's normal to have explicit self's all over your Python code. If you try tricks to avoid that you will be making your code difficult to read for other Python programmers (and potentially introducing extra bugs)

提交回复
热议问题