63

我有一个 python 脚本,我收到以下错误:

Traceback (most recent call last):
  File "C:\Users\Tim\Desktop\pop-erp\test.py", line 1, in <module>  
  s = Something()
  NameError: name 'Something' is not defined

这是导致问题的代码:

s = Something()
s.out()

class Something:
    def out():
        print("it works")

这是在 Windows 7 x86-64 下使用 Python 3.3.0 运行的。

为什么找不到Something类?

4

3 回答 3

98

在使用之前定义类:

class Something:
    def out(self):
        print("it works")

s = Something()
s.out()

您需要self作为第一个参数传递给所有实例方法。

于 2013-02-10T23:59:22.627 回答
16

Note that sometimes you will want to use the class type name inside its own definition, for example when using Python Typing module, e.g.

class Tree:
    def __init__(self, left: Tree, right: Tree):
        self.left = left
        self.right = right

This will also result in

NameError: name 'Tree' is not defined

That's because the class has not been defined yet at this point. The workaround is using so called Forward Reference, i.e. wrapping a class name in a string, i.e.

class Tree:
    def __init__(self, left: 'Tree', right: 'Tree'):
        self.left = left
        self.right = right
于 2019-12-04T17:17:20.953 回答
3

您必须在创建类的实例之前定义类。将调用移动Something到脚本的末尾。

您可以尝试本末倒置,并在定义之前调用程序,但这将是一个丑陋的黑客攻击,您必须按照此处定义的方式滚动:

使python文件中的函数定义独立于顺序

于 2013-02-10T23:58:47.820 回答