Python NameError The class of the name is not defined 但实际上是

标签 python class

我在玩类,我想创建一个名为 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/

相关文章:

python - pyspark - 使用 ArrayType 列折叠和求和

c++防止通过getter更改引用

c# - 为什么C#创建对象时要选择接口(interface)类型?

python - 如何找到两个特殊字符之间的字符串?

python - 检查列表值

python - PyGitHub:获取存储库的提交总数

python - 我当前的二叉搜索树实现有什么问题?最后打印树只打印根

python - 在循环或 if 语句中实例化类在编程上是否正确?

class - UML 类图

c++ - 在 C++ 中什么时候应该使用类还是结构?