不能在 Python 中使用 class 构造函数参数

Can't use class constructor argument in Python

我不明白我做错了什么。我正在使用以下代码定义 class:

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...

然后,当我尝试创建 class

的实例时
base = database("mydb.db")

我收到一条错误消息,指出没有 "global" 名为 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 的正确方法是什么?

这段代码看起来不错。错误不在您 post 编辑的代码中;它位于 createDBfile() 方法第 15 行的 testdb.py 中(不在 __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

如第一行所说,最近的通话是 last。所以你从下到上(而不是从上到下)读取回溯。

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

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

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

上面是对 __init__() 函数中 createDBfile() 方法的调用,上面是对 __init__() 函数的调用(通过创建 class 实例).

你没有post这个createDBfile()方法的内容,所以我不能告诉你具体错误在哪里。我怀疑您在函数参数方面做错了(也许只是打字错误?)