【问题标题】:Dataclasses in Python: What to do with complex types as arguments?Python 中的数据类:如何处理复杂类型作为参数?
【发布时间】:2021-03-23 05:36:36
【问题描述】:

我已经开始接受主要是数据容器的类的数据类装饰器。我看到的所有教程和示例都是针对相对简单的变量,类型有 int、str、float、list、tuple 或 dict。我对数据类有两个问题:

  1. 我从未见过数据类中实现了哪些类型的列表。

  2. 我从未见过如何处理未在数据类中实现的类型的示例。

第二个问题是这篇文章的重点。那么,如果您的数据类具有更复杂的属性(例如,pandas 数据框、函数、用户生成类的实例),是否有方法或最佳实践?我可以想到两个可能的选择:a)在 _post_init_ 中手动处理复杂类型,或者 b)“构建”一个描述参数的类型(我不知道该怎么做,这似乎是可能的)

这大概是我实现选项 a 的方式:

from dataclasses import dataclass

@dataclass
class movie:
    release_year: int
    title: str

    def __post_init__(self, cast_table):
        cast_table = cast_table # A dataframe containing cast information

【问题讨论】:

  • cast_table 是什么类型?如果它的类型为Foo,您只需将cast_table: Foo 添加到您的一系列属性中。 : 之后的部分必须是一个类型。
  • 根据作业中的注释, cast_table 是一个数据框。所以你是说我可以把cast_table: pd.core.frame.DataFrame 放在属性中?嗯,我确定我之前尝试过,但没有成功。
  • 即使有自我回答,这个问题对我来说也没有意义。你能澄清一下你到底在问什么吗? “数据类中实现了哪些类型”是什么意思? dataclass 根本不关心其字段的类型,但为 dataclasses 模块记录的标记除外。 dataclass 装饰器没有针对任何特定的属性类型实现,它适用于所有这些类型。
  • @MisterMiyagi,是的,这就是我没有明白的重点。我一直在假设装饰器必须为每种类型都有“处理程序”。我只是从未想过它可以通用地处理它们。

标签: python python-typing python-dataclasses


【解决方案1】:

根据chepner 的评论,这里是:如何做我所要求的:

from dataclasses import dataclass
import pandas as pd

@dataclass
class movie:
    release_year: int
    title: str
    cast_table: pd.core.frame.DataFrame

tabl = pd.DataFrame(data={'Actor': ['Graham Chapman', 'John Cleese', 'Eric Idle'], 'Role': ['King Arthur', 'Sir Lancelot', 'Sir Robin']})
mphg = movie(title='Monty Python and the Holy Grail', release_year=1975 cast_table=tabl)

【讨论】:

    【解决方案2】:

    它有效,但你有没有找到一种方法来产生比这更好的输出?

    movie(release_year=1975, title='Monty Python and the Holy Grail', 
    cast_table=            Actor          Role
    0  Graham Chapman   King Arthur
    1     John Cleese  Sir Lancelot
    2       Eric Idle     Sir Robin)
    

    这很好,因为它就像为年份和标题聚合的数据透视表输出。但它只是在屏幕上很乱,并且将这些数据作为 DataFrame 运行有点挑战。你知道让输出变成这样的方法吗......

        Actor            Role         release_year        title 
    0  Graham Chapman   King Arthur    1975        'Monty Python and the Holy Grail'
    1  John Cleese      Sir Lancelot   1975        'Monty Python and the Holy Grail'      
    2  Eric Idle        Sir Robin      1975        'Monty Python and the Holy Grail'
    

    相反?........

    此外,您在 cast_table = tabl 中省略了逗号“,”

    mphg = movie(title='Monty Python and the Holy Grail', release_year=1975 cast_table=tabl)
    

    修正

    mphg = movie(title='Monty Python and the Holy Grail', release_year=1975, cast_table=tabl)
    

    【讨论】:

    • 看起来它超出了这个问题的范围,更多的是一个新问题。您可以重新定义__repr__ 方法以获得您喜欢的输出,尽管建议__repr__ 方法的输出看起来像可以调用它来创建实例。喜欢movie(title='Monty Python and the Holy Grail', release_year=1975)。最好为您选择的输出实现自定义方法,例如print_table() 或其他东西。
    猜你喜欢
    • 2012-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 2015-05-05
    • 2015-12-13
    • 2021-12-25
    相关资源
    最近更新 更多