gpt4 book ai didi

python - 自动生成的 Python 构造函数

转载 作者:太空宇宙 更新时间:2023-11-03 13:52:03 24 4
gpt4 key购买 nike

我有无数来自 SQLAlchemy 的各种项目的 Python 类(还有一些来自 Pygame),我最近注意到其中许多有一个模式:它们的构造函数总是像这样:

class Foo(Base):
def __init__(self, first, last, email, mi=""):
self.first = first
self.last = last
self.email = email
self.mi = mi

...构造函数所做的唯一一件事就是将一组位置参数传输到一组完全相同的命名数据成员中,不执行任何计算或其他函数调用。

在我看来,这种重复是不必要的,并且在更改时容易出现人为错误。

这让我想到了这里的问题:是否有可能自动生成这样一个 __init__(self, ...) 函数,最好不要乱用 CPython 字节码或使用模板/宏来改变源文件本身?

最佳答案

对于 python >= 3.7,处理这个问题的正确方法是通过 dataclasses :

This module provides a decorator and functions for automatically adding generated special methods such as __init__() and __repr__() to user-defined classes. It was originally described in PEP 557.

关于python - 自动生成的 Python 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5931474/

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