python class 属性打印错误,我哪里出错了?

Printing error with python class attributes, where have I gone wrong?

我正在尝试打印电子表格中的 select 行和列,但是当我调用电子表格数据框属性时,它无法打印名称数据框未定义的状态。我哪里做错了?

import pandas

class spreadsheet:
    def __init__(self, location, dataframe, column, rows):
        self.location = ('Readfrom.xlsx')
        self.dataframe = pandas.read_excel(location)
        self.column = 2
        self.rows = 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 27, 28, 29

a = dataframe.iloc[column,[rows]]

print(a)

我认为你的缩进有问题。

您的 dataframespreadsheet 构造函数方法的一个参数,您甚至试图从 class.

外部访问它

要访问 dataframe 变量,您必须将代码 a = dataframe.iloc[column,[rows]] 移动到 __init__ 方法中,或者您需要先创建一个 spreadsheet 对象并通过这个对象。

编辑:

再三考虑,我认为您应该查看 Python.

中如何使用 classes 的基础知识
  1. 你不使用 __init__ 的参数,为什么你有它们?
  2. dataframe 只能由电子表格对象访问

此代码应该可以解决您的问题,但我建议您阅读一些基本教程以了解 classes 和对象的工作原理:

import pandas

class spreadsheet:
    def __init__(self):
        self.location = ('Readfrom.xlsx')
        self.dataframe = pandas.read_excel(self.location)
        self.column = 2
        self.rows = 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 27, 28, 29

s = spreadsheet()
a = s.dataframe.iloc[s.column,[s.rows]]

print(a)

您应该从电子表格 class 实例化一个对象,然后访问该实例的属性。您可以在 Python here.

中了解有关面向对象编程的更多信息

我认为您想在代码中执行的操作类似于下面的代码。

import pandas

class Spreadsheet:
    def __init__(self, location):
        self.location = location
        self.dataframe = pandas.read_excel(location)


sp = Spreadsheet(location="Readfrom.xlsx")

rows = [4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 27, 28, 29]

a = sp.dataframe.iloc[rows, 2]

print(a)