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

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

问题描述

所以我有一个类,我用作本地命名空间。我在类中有一些静态函数,但是他们不能访问类范围变量。为什么是这样?

  class Foo:
foo_string =I am a foo

@staticmethod
def foo():
print foo_string






 >>> Foo.foo()
[Stack Trace]
NameError:未定义全局名称'foo_string'


b $ b

任何想法?

解决方案

Python不允许类变量落入这个范围,方法这样做,第一个是使用类方法:

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

我认为这是最好的解决方案。 p>

第二个是按名称访问:

  @staticmethod 
def foo():
print(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天全站免登陆