如何在没有自我的情况下访问类范围的变量? [英] How to access class-scope variables without self?

查看:31
本文介绍了如何在没有自我的情况下访问类范围的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个类,我将它用作本地命名空间.我在类中有一些静态函数,但它们无法访问类作用域变量.这是为什么?

 类 Foo:foo_string = "我是一个 foo"@静态方法定义 foo():打印 foo_string

<小时><预><代码>>>>foo.foo()[堆栈跟踪]NameError: 全局名称 'foo_string' 未定义

有什么想法吗?

解决方案

Python 不会让类变量以这种方式落入作用域,有两种方法可以做到这一点,第一种是使用类方法:

@classmethoddef foo(cls):打印(cls.foo_string)

我认为这是最好的解决方案.

第二种是按名字访问:

@staticmethod定义 foo():打印(Foo.foo_string)

请注意,一般而言,使用类作为命名空间并不是最好的方法,只需使用具有顶级函数的模块即可,因为这更符合您的意愿.

之所以没有这样的作用域,主要是因为Python的动态特性,当你在类中插入一个函数时它会如何工作?它必须有条件地添加特殊行为,这将非常难以实施并且可能很脆弱.它还有助于保持显式而不是隐式 - 很清楚什么是类变量而不是局部变量.

So I have a class, which I'm using as a local namespace. I have some static functions in the class, but they can't access the class scope variables. Why is this?

class Foo:
    foo_string = "I am a foo"

    @staticmethod
    def foo():
        print foo_string


>>> Foo.foo()
  [Stack Trace]
  NameError: global name 'foo_string' is not defined

Any thoughts?

解决方案

Python doesn't let class variables fall into scope this way, there are two ways to do this, the first is to use a class method:

@classmethod
def foo(cls):
    print(cls.foo_string)

Which I would argue is the best solution.

The second is to access by name:

@staticmethod
def foo():
    print(Foo.foo_string)

Do note that in general, using a class as a namespace isn't the best way to do it, simply use a module with top-level functions instead, as this acts more as you want to.

The reason for the lack of scoping like this is mainly due to Python's dynamic nature, how would it work when you insert a function into the class? It would have to have special behaviour added to it conditionally, which would be extremely awkward to implement and potentially fragile. It also helps keep things explicit rather than implicit - it's clear what is a class variable as opposed to a local variable.

这篇关于如何在没有自我的情况下访问类范围的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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