我在玩类,我想创建一个名为 Container 的类,用于将所有可以容纳其他东西的东西分组。
# -*- coding: utf-8 -*-
class Container(object):
def __init__(self, name, volume):
self.name = name
self.max_volume = volume
hands = Container('HANDS', 2)
我从这一点开始然后我想测试是否一切正常但是如果在 python 控制台中我调用 hands.name
它说 hands
没有定义.当我将其作为模块导入时也会发生这种情况。
我不明白我做错了什么!你能解释一下如何让它发挥作用吗?
我从 python 控制台得到:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'hands' is not defined
最佳答案
假设这是 container.py
文件:
# -*- coding: utf-8 -*-
class Container(object):
def __init__(self, name, volume):
self.name = name
self.max_volume = volume
hands = Container('HANDS', 2)
这是你在解释器中的执行命令:
>>> import container
然后,可以通过以下方式访问 hands
实例:
>>> container.hands.name
为了避免container
前缀,你也可以这样做:
>>> from container import hands
>>> hands.name
关于Python NameError The class of the name is not defined 但实际上是,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30562669/