将数据存储在类中,并动态访问数据作为类属性
我正在尝试编写一个类,该类将数据框架ID作为字符串和值作为数据框的值,并创建访问数据的类属性。
我能够编写一个类似类的小例子,该类别需要以静态方式创建的方法并将对象返回为类方法,但我想循环浏览数据,以 df的键键入键
s,并允许使用属性访问每个 df
。
最低工作示例
from dataclasses import dataclass
import pandas as pd
# re-writing as dataclass
@dataclass
class Dataset:
# data container dictionary as class attribute
dict = {'df1_id':pd.DataFrame({'col1':[1,1]}),
'df2_id':pd.DataFrame({'col2':[2,2]}),
'df3_id':pd.DataFrame({'col3':[3,3]})}
def df1_id(self) -> pd.DataFrame:# class method to create as class attribute
return dict['df1_id']
def df2_id(self) -> pd.DataFrame:# same class method above
return dict['df2_id']
def df3_id(self) -> pd.DataFrame:# same class method above
return dict['df3_id']
def dataframes_as_class_attributes(self):
# store the dfs to access as class attributes
# replacing 3 methods above
return
结果
datasets = Dataset()
print(datasets.df1_id())
预期结果
datasets = Dataset()
print(datasets.df1_id) # class attribute created by looping through the dict object
编辑:
- 与此相似:如何将CSV文件的内容读取到一个将每个CSV行作为类实例上课
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
似乎班级的唯一目的是具有属性访问语法。在这种情况下,只需创建a >对象。
输出:
It seems that the only purpose of the class is to have attribute access syntax. In that case, it would be simpler to just create a namespace object.
Output:
您可以使用
setAttr
如下所示:为了避免与Python关键字发生冲突,将单个尾随下划线放置在变量名称之后。 ( pep 8 )
You could use
setattr
like below:To avoid conflicts with python keywords put a single trailing underscore after variable name. (PEP 8)