How to access class-scope variables without self?

落花浮王杯 提交于 2019-12-29 06:44:43

问题


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?


回答1:


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.




回答2:


Python is versatile language, you can even change your syntax, but is it wise? There is one solution:

class test():

    def __init__(self, **args):
        for a in args.keys():
            setattr(self, a, args[a]) #store a given variable name and corresponding value

    def __call__(self, function):
        ''' run functions by using object's namespace, when object is called'''

        # run a code described in self.function by using namespace self.__dict__
        exec(getattr(self, function).__code__, self.__dict__)

    def testA():
        '''
        * Special function without self as argument
        * Using namespace described in self.__dict__
        * Can not return anything
        * Call by command self('testA') or <class>('testA')
        '''
        print(name)

    def testB(self):
        self('testA') # Call function testA




prog = test(name = 'python')
prog('testA') # Function testA prints python
prog.testB() # Function testB calls testA
input()


来源:https://stackoverflow.com/questions/13037426/how-to-access-class-scope-variables-without-self

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!