python类实例化,Python在类定义中实例化类

在Python中尝试在类定义内部初始化一个包含类实例的列表时遇到了问题,错误显示变量'Classy'未定义。这是因为类体在创建之前执行,导致无法在其中引用自身。为了解决这个问题,需要在类体外部创建实例并将其添加到类的静态变量中。然而,这样的设计可能需要慎重考虑,因为全局列表通常不是最佳实践。建议在需要时动态创建和管理此类列表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值