类实例作为静态属性 [英] Class instance as static attribute

查看:70
本文介绍了类实例作为静态属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 3不允许您在其主体内部引用类(方法中除外):

Python 3 doesn't allow you to reference a class inside its body (except in methods):

class A:
    static_attribute = A()

    def __init__(self):
        ...

这会在第二行中引起一个NameError,因为'A' is not defined.

This raises a NameError in the second line because 'A' is not defined.

我很快找到了一种解决方法:

I have quickly found one workaround:

class A:
    @property
    @classmethod
    def static_property(cls):
        return A()

    def __init__(self):
        ...

尽管这并不完全相同,因为它每次都会返回一个不同的实例(您可以通过将实例第一次保存到静态变量中来避免这种情况).

Although this isn't exactly the same since it returns a different instance every time (you could prevent this by saving the instance to a static variable the first time).

有没有更简单和/或更优雅的选择?

Are there simpler and/or more elegant alternatives?

我已将有关此限制原因的问题移至单独的问题

I have moved the question about the reasons for this restriction to a separate question

推荐答案

在定义类A之前,不能运行表达式A().在您的第一段代码中,A的定义在您尝试执行A()时还不完整.

The expression A() can't be run until the class A has been defined. In your first block of code, the definition of A is not complete at the point you are trying to execute A().

这是一个更简单的选择:

Here is a simpler alternative:

class A:
    def __init__(self):
        ...

A.static_attribute = A()

这篇关于类实例作为静态属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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