【问题标题】:Can't use class constructor argument in Python不能在 Python 中使用类构造函数参数
【发布时间】:2016-03-24 14:22:16
【问题描述】:

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

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 的正确方法是什么?

【问题讨论】:

  • 这就是你的代码...?因为它已损坏和/或格式错误。请仔细检查您在此处粘贴的内容,尤其是缩进。
  • 我修复了重复的“类数据库:”这行是你的意思吗?

标签: python class arguments init


【解决方案1】:

这段代码看起来不错。错误不在您发布的代码中;它在 createDBfile() 方法的第 15 行的 testdb.py 中(不在 __init__() 中)。

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

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 行中,在方法@​​987654327@ 中发生了错误。 Python 还会打印出这行 15 的内容。

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

你没有发布这个createDBfile()方法的内容,所以我不能告诉你错误到底在哪里。我怀疑你在函数参数上做错了(也许就像一个错字一样简单?)

【讨论】:

  • 你绝对正确,谢谢!我在 createDBfile 方法的定义中为 filename 变量使用了不同的名称,然后忘记了!
猜你喜欢
  • 2015-12-22
  • 2020-03-06
  • 2017-04-01
  • 2013-08-03
  • 1970-01-01
  • 2016-09-02
  • 2021-03-18
  • 2023-01-15
  • 1970-01-01
相关资源
最近更新 更多