Python在类定义中实例化类 [英] Python Instantiate Class Within Class Definition

查看:434
本文介绍了Python在类定义中实例化类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向类中添加一个变量来保存类的实例。以下是我的代码的缩写版本。

I am attempting to add a variable to a class that holds instances to the class. The following is a shortened version of my code.

class Classy :
    def __init__(self) :
        self.hi = "HI!"
    # "CLASSIES" variable holds instances of class "Classy"
    CLASSIES = []
    for i in xrange(0,4) :
        CLASSIES.append(Classy())

运行代码时,出现以下错误。

Upon running the code, I get the following error.

Traceback (most recent call last):
  File "classy.py", line 6, in Classy
    CLASSIES.append(Classy())
NameError: name 'Classy' is not defined

一个类到该类中的一个类/静态变量?

Is there another way to add instances of a class to a class/static variable within that class?

推荐答案

类主体在创建类之前执行。因此,您试图在存在之前实例化类。你仍然可以附加实例到类,但是你必须在类体完成后创建它们,例如:

The class body is executed before the class is created. Therefore, you are attempting the instantiate the class before it exists. You can still attach instances to the class, but you have to create them after the class body finished, e.g.:

class Classy(object):
    def __init__(self):
        self.hi = "HI!"
    CLASSIES = []

for i in xrange(4):
    Classy.CLASSIES.append(Classy())

然而,我建议你首先想一下,无论你是否真的需要这个有效的全局列表,以及你是否需要它是类的一部分目的。就我个人而言,我几乎从不做这样的事情。

However, I'd suggest you first think long and hard whether you actually need this effectively-global list, and whether you need it to be part of the class object. Personally, I almost never do something like this.

这篇关于Python在类定义中实例化类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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