Python NameError名称的类未定义,但实际上是 [英] Python NameError The class of the name is not defined but it actually is

查看:95
本文介绍了Python NameError名称的类未定义,但实际上是的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当时在玩类,因此我想创建一个名为Container的类,该类用于将所有可以容纳其他东西的东西分组。

I was playing with classes and I thought to create a class called Container which is meant to group all things that can hold other things.

# -*- 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 ,它说没有定义。当我也将其导入为模块时,就会发生这种情况。

I started from this point and then I wanted to test if everything was ok but if in the python console I call hands.name it says that hands is not defined. This happens when I import it as a module too.

我没有弄错我的意思!

I don't get what I am doint wrong! Can you please explain me how to make it work?

我是从python控制台获得的:

I get from the python console:

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)

这是您在解释器中的执行命令:

and this is your execution command in the interpreter:

>>> import container

然后, hands 实例为可通过以下方式访问:

Then, the hands instance is accessible in the following manner:

>>> container.hands.name

避免使用容器前缀,您也可以执行以下操作:

To avoid the container prefix, you can also do this:

>>> from container import hands
>>> hands.name

这篇关于Python NameError名称的类未定义,但实际上是的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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