我如何访问“静态"Python中类方法中的类变量? [英] How can I access "static" class variables within class methods in Python?

查看:71
本文介绍了我如何访问“静态"Python中类方法中的类变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下python代码:

If I have the following python code:

class Foo(object):
    bar = 1

    def bah(self):
        print(bar)

f = Foo()
f.bah()

它抱怨

NameError: global name 'bar' is not defined

如何在方法 bah 中访问类/静态变量 bar?

How can I access class/static variable bar within method bah?

推荐答案

使用 self.barFoo.bar 代替 bar.赋值给 Foo.bar 将创建一个静态变量,赋值给 self.bar 将创建一个实例变量.

Instead of bar use self.bar or Foo.bar. Assigning to Foo.bar will create a static variable, and assigning to self.bar will create an instance variable.

这篇关于我如何访问“静态"Python中类方法中的类变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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