从静态变量引用静态方法 [英] Refering to static methods from static variables

查看:52
本文介绍了从静态变量引用静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 python 2.7 中,我想创建一个静态变量来存储运行封闭类的静态方法的结果.

我尝试了以下方法:

A 类:@静态方法定义 foo():返回 1v = A.foo() # 一个静态变量打印AV

返回错误:

NameError: name 'A' 未定义

然而,引用另一个类的静态变量是有效的:

B 类:@静态方法定义 foo():返回 1A类:@静态方法定义 foo():返回 1v = B.foo()打印AV>>>1

有什么解释吗?

此场景的用例是缓存 foo 的结果,并将其包含在 A 的命名空间下.根据答案,我了解到 A 在执行时尚未定义,这会导致错误.我想出了以下方法来延迟计算:

A 类:@静态方法定义 foo():打印运行 foo"返回 1@静态方法def get_v():尝试:返回 A.v除了属性错误:A.v = A.foo()返回 A.v打印 A.get_v()打印 A.get_v()>>>运行 foo>>>1>>>1

这似乎可以完成工作,但有点麻烦.

解决方案

使用@classmethod,并将值缓存在类对象上.

S 类(对象):@类方法def f(klass):如果没有 hasattr(klass, '_f'):打印计算值"klass._f = 5返回 klass._f

当从不同实例调用两次时:

<预><代码>>>>s = S()>>>s2 = S()>>>s.f()计算值5>>>s2.f()5

该值由 S 的所有实例共享.

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.

解决方案

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.

这篇关于从静态变量引用静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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