gpt4 book ai didi

python - 如何将参数传递给 __init__ 函数

转载 作者:太空宇宙 更新时间:2023-11-04 09:52:06 27 4
gpt4 key购买 nike

我开始了我的 Python 之旅。我想创建一个程序,将我的 xlsx 文件转换为 sql 文件,然后将数据加载到数据库中。

我想创建一个有两个参数的类:

  • ex - 将打开 xlsx 工作簿
  • sh - 将使用正确的索引从 ex 打开工作表

这是初始版本(现在我只是打印行):

class XToSql():
def __init__(self, ex = xlrd.open_workbook('ex1.xlsx'), sh = ex.sheet_by_index(0)):
self.ex = ex
self.sh = sh

def modify(self):
for i in str((self.sh.nrows-1)):
a = 1
print(self.sh.row_values(a))
a += 1

a1 = XToSql()
a1.modify()

__init__函数中,这一行用红色标记:sh = ex.sheet_by_index(0) -> 运行后出现这个错误:def __init__(self, ex = xlrd.open_workbook('ex1.xlsx'), sh = ex.sheet_by_index(0)):

NameError: name 'ex' is not defined

知道我做错了什么吗?

最佳答案

__init__ 的参数列表中,ex 还没有被评估,所以 sh = ex.sheet_by_index(0)) 正在抛出名称错误。这发生在创建类对象时。

您可以做几件事。编写类的一个原因是您可以重用它,因此也许该类应该只将文件路径作为参数。

class XToSql():

def __init__(self, ex_file):

self.ex = xlrd.open_workbook(ex_file)
self.sh = self.ex.sheet_by_index(0)

def modify(self):
for i in str(self.sh.nrows - 1):
a = 1
print(self.sh.row_values(a))
a += 1

也许您应该能够指定要处理的工作表

class XToSql():

def __init__(self, ex_file, sheet=0):

self.ex = xlrd.open_workbook(ex_file)
self.sh = self.ex.sheet_by_index(sheet))

def modify(self):
for i in str(self.sh.nrows - 1):
a = 1
print(self.sh.row_values(a))
a += 1

然后像这样使用它

a = XToSql(ex_file='ex1.xlsx', sheet=0)

关于python - 如何将参数传递给 __init__ 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47368573/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com