如何访问类成员变量?

新手上路,请多包涵
class Example(object):
    def the_example(self):
        itsProblem = "problem"

theExample = Example()
print(theExample.itsProblem)

如何访问类的变量?我试过添加这个定义:

 def return_itsProblem(self):
    return itsProblem

然而,那也失败了。

原文由 Adam 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 780
2 个回答

答案,几句话

在您的示例中, itsProblem 是局部变量。

您必须使用 self 来设置和获取实例变量。可以在 __init__ 方法中设置。那么你的代码将是:

 class Example(object):
    def __init__(self):
        self.itsProblem = "problem"

theExample = Example()
print(theExample.itsProblem)

但是如果你想要一个真正的类变量,那么直接使用类名:

 class Example(object):
    itsProblem = "problem"

theExample = Example()
print(theExample.itsProblem)
print (Example.itsProblem)

但要小心这个,因为 theExample.itsProblem 自动设置为等于 Example.itsProblem ,但根本不是同一个变量,可以独立更改。

一些解释

在 Python 中,变量可以动态创建。因此,您可以执行以下操作:

 class Example(object):
    pass

Example.itsProblem = "problem"

e = Example()
e.itsSecondProblem = "problem"

print Example.itsProblem == e.itsSecondProblem

印刷

真的

因此,这正是您对前面的示例所做的。

事实上,在 Python 中,我们使用 self as this ,但它不止于此。 self 是任何对象方法的第一个参数,因为第一个参数始终是对象引用。这是自动的,无论您是否称它为 self

这意味着你可以这样做:

 class Example(object):
    def __init__(self):
        self.itsProblem = "problem"

theExample = Example()
print(theExample.itsProblem)

要么:

 class Example(object):
    def __init__(my_super_self):
        my_super_self.itsProblem = "problem"

theExample = Example()
print(theExample.itsProblem)

完全一样。 ANY对象方法的第一个参数是当前对象,我们只称呼它 self 作为约定。 您只需向该对象添加一个变量,就像您从外部执行此操作一样。

现在,关于类变量。

当你这样做时:

 class Example(object):
    itsProblem = "problem"

theExample = Example()
print(theExample.itsProblem)

您会注意到我们首先 设置了一个类变量,然后我们访问 了一个对象(实例)变量。我们从未设置过这个对象变量,但它有效,这怎么可能?

好吧,Python 会首先尝试获取对象变量,但如果找不到,则会给您类变量。 警告:类变量在实例之间共享,而对象变量则不然。

作为结论,永远不要使用类变量来为对象变量设置默认值。为此使用 __init__

最终,您将了解到 Python 类是实例,因此是对象本身,这为理解上述内容提供了新的见解。一旦你意识到这一点,请稍后再回来阅读。

原文由 e-satis 发布,翻译遵循 CC BY-SA 4.0 许可协议

您声明的是局部变量,而不是类变量。要设置实例变量(属性),请使用

class Example(object):
    def the_example(self):
        self.itsProblem = "problem"  # <-- remember the 'self.'

theExample = Example()
theExample.the_example()
print(theExample.itsProblem)

要设置 类变量(也称为静态成员),请使用

class Example(object):
    def the_example(self):
        Example.itsProblem = "problem"
        # or, type(self).itsProblem = "problem"
        # depending what you want to do when the class is derived.

原文由 kennytm 发布,翻译遵循 CC BY-SA 2.5 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题