Refering to static methods from static variables

牧云@^-^@ 提交于 2020-04-17 06:59:07

问题


In python 2.7, I want to create a static variable which stores the result of running a static method of the enclosing class.

I tried the following:

class A:
    @staticmethod
    def foo():
            return 1
    v = A.foo() # a static variable
print A.v

which returns the error:

NameError: name 'A' is not defined

However, referring to another class' static variable works:

class B:
    @staticmethod
    def foo():
            return 1
class A:
    @staticmethod
    def foo():
            return 1
    v = B.foo()

print A.v

>>> 1

Any explanations?

EDIT:

The use-case for this scenario is caching the result of foo, and enclose it under A's name space. Following the answers I understand that A is not yet defined at the execution time, which leads to an error. I came up with the following to delay the computation:

class A:
    @staticmethod
    def foo():
            print 'running foo'
            return 1

    @staticmethod
    def get_v():
            try:
                    return A.v
            except AttributeError:
                    A.v = A.foo()
                    return A.v

print A.get_v()
print A.get_v()

>>> running foo
>>> 1
>>> 1

This seems to do the job, but is somewhat cumbersome.


回答1:


Use @classmethod, and cache the value on the class object.

class S(object):
    @classmethod
    def f(klass):
        if not hasattr(klass, '_f'):
            print "Calculating value"
            klass._f = 5

        return klass._f

When called twice from different instances:

>>> s = S()
>>> s2 = S()
>>> s.f()
Calculating value
5
>>> s2.f()
5

The value is shared over all instances of S.




回答2:


Apart from wondering why you're doing this: at the time you assign v (in the line v = A.foo(), A has not been defined yet. (The definition of A is the entire class block, so A isn't defined until after that block.)

In your second example, B is already defined when you say v = B.foo().

EDIT: What puzzles me is the following:

class A:
    @staticmethod
    def foo():
        return 1
    v = foo()

Running this code results in

    v = foo()
TypeError: 'staticmethod' object is not callable



回答3:


You cannot call a (static) method from class A until the class is fully defined (end of block class). But you can define a static variable as soon as the class is defined:

class A:
    @staticmethod
    def foo():
        print "running foo"
        return 1
A.v = A.foo()

You can then use anywhere

print A.v


来源:https://stackoverflow.com/questions/35863305/refering-to-static-methods-from-static-variables

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