[英]Python NameError The class of the name is not defined but it actually is
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. 我当时在玩类,我想创建一个名为Container的类,该类旨在将可以容纳其他物品的所有物品分组。
# -*- coding: utf-8 -*-
class Container(object):
def __init__(self, name, volume):
self.name = name
self.max_volume = volume
hands = Container('HANDS', 2)
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. 我从这一点开始,然后我想测试一切是否正常,但是如果在python控制台中我调用hands.name
它表示未定义hands
。 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? 您能给我解释一下如何使其工作吗?
I get from the python console: 我从python控制台获得:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'hands' is not defined
Assuming this is the container.py
file: 假设这是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
Then, the hands
instance is accessible in the following manner: 然后,可以通过以下方式访问hands
实例:
>>> container.hands.name
To avoid the container
prefix, you can also do this: 为了避免container
前缀,您还可以执行以下操作:
>>> from container import hands
>>> hands.name
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.