我应该使用“全局”或“自身”。 Python中的类范围变量? [英] Should I be using "global" or "self." for class scope variables in Python?

查看:155
本文介绍了我应该使用“全局”或“自身”。 Python中的类范围变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两个代码块都可以工作。是否有正确的方法来做到这一点?

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
    def inc(self):
        return globx + 1

myStuff = Stuff(3)
print myStuff.inc()

打印4

class Stuff:
    def __init__(self, x = 0):
        self.x = x
    def inc(self):
        return self.x + 1

myStuff = Stuff(3)
print myStuff.inc()

还打印4

我是一个noob,我正在使用很多变量一类。开始想知道为什么我把自我。

I'm a noob, and I'm working with a lot of variables in a class. Started wondering why I was putting "self." in front of everything in sight.

感谢您的帮助!

推荐答案

p>你应该使用第二种方式,然后每个实例都有一个单独的 x

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

那么当您有多个 Stuff 实例时,您可能会发现您会得到令人惊讶的结果,因为更改一个实例会影响所有其他实例。

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.

在你的Python代码中有明确的自我是正常的。如果你试图避免你的代码难以读取其他Python程序员(并可能引入额外的错误)

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)

这篇关于我应该使用“全局”或“自身”。 Python中的类范围变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆