不能在Python

时间:2016-03-24 14:22:16

标签: python class arguments init

我无法理解我在这里做错了什么。我使用以下代码定义了一个类:

import sqlite3 as lite
import sys 
import os.path
class database:
    def __init__(self,dbfname):
       if os.path.isfile(dbfname):
            self.con = lite.connect(dbfname)
       else:
            self.con = self.createDBfile(dbfname)
    #Other methods...

然后,当我尝试创建类的实例时

base = database("mydb.db")

我收到一条错误消息,说没有"全球"变量名为 dbfname

Traceback (most recent call last):
File "testdb.py", line 67, in <module>
base = database("mydb.db")
File "testdb.py", line 13, in __init__
self.con = self.createDBfile(dbfname)
File "testdb.py", line 15, in createDBfile
if os.path.isfile(dbfname):
NameError: global name 'dbfname' is not defined

使用参数变量dbfname的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

此代码看起来很好。您发布的代码中的错误不是;它位于testdb.py方法第15行的createDBfile()中(不在__init__()中)。

我怎么知道这个?好吧,让我们仔细看看Python给我们的追溯:

Traceback (most recent call last):
  File "testdb.py", line 67, in <module>
    base = database("mydb.db")
  File "testdb.py", line 13, in __init__
    self.con = self.createDBfile(dbfname)
  File "testdb.py", line 15, in createDBfile
    if os.path.isfile(dbfname):
NameError: global name 'dbfname' is not defined

就像第一行所说,最近的通话是最后一次。所以你从下到上阅读了追溯(而不是从上到下)。

最后一行是实际错误,但就在此之前:

  File "testdb.py", line 15, in createDBfile
    if os.path.isfile(dbfname):

所以它说文件testdb.py,在第15行,在方法createDBfile()中发生错误。 Python还打印出这行15的内容。

上面是对createDBfile()函数中__init__()方法的调用,以及对__init__()函数的调用(通过创建类实例)。

您没有发布此createDBfile()方法的内容,因此我无法告诉您错误的确切位置。我怀疑你对函数参数做了一些错误(也许就像拼写错误一样简单?)