python - 有没有更 pythonic 的方法来为一个类设置多个默认参数?

标签 python class constructor default-arguments

我有一个有很多默认值的类,因为我不能重载函数。有没有比使用多个默认参数或使用 kwargs 更好的方法?

我考虑过将字典传递到我的类中,但我该如何控制是否传递必要的参数?

是否有更 pythonic 的方式允许参数而不将它们全部定义为默认值?

例如,我允许许多默认值:

class Editor:
    def __init__(self,
                 ffmpeg: str,
                 font_file=None,
                 font_size=148,
                 font_color="white",
                 title_length=5,
                 title_x="(w-text_w)/2",
                 title_y="(h-text_h)/2",
                 box=1,
                 box_color="black",
                 box_opacity=0.5,
                 box_border_width=25):

        self.ffmpeg = ffmpeg

        self.title s= define_title(
            font_file, font_size, font_color, title_length)

        self.box = define_box(
            box, box_color, box_opacity, box_border_width},

        self.coordinates = {"x": title_x, "y": title_y}

在其他语言中我可能会重载构造函数的地方。

最佳答案

如果您希望它们非常标准,您可以在类对象本身上指定默认属性,然后可以在需要时通过在实例上重新分配这些属性来掩盖这些属性。如果您希望传入不同的参数组,您还可以使用 @classmethod 创建多个构造函数。

class Editor(object):
    font_file = None
    font_size = 148
    def __init__(self, ffmpeg=str):
        self.ffmpeg = ffmpeg
    @classmethod
    def with_box(cls, ffmpeg=str, box=1):
        new_editor = cls(ffmpeg)
        new_editor.box = box
        return new_editor

然后你会调用:

Editor.with_box(ffmpeg=int, box=2)

并取回一个正确框初始化的编辑器实例。

关于python - 有没有更 pythonic 的方法来为一个类设置多个默认参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39502385/

相关文章:

python - 在 Python 中解析 1 亿条 A 记录的最快方法

python - 在python中将一个json字典添加到另一个json字典中

python - Python 嵌套字典的逆序

C++ 多重继承构造函数

inheritance - C# - 构造函数和继承

python - estimator 应该是一个实现 'fit' 方法的估计器

java - 在 Eclipse 中使用 Apache Commons Math

class - dart:对于语法专家,如何在嵌套类中交换子树

class - 如何在 Object Pascal "class of interface"(或 "interface of interface")类型中创建

c++ - 类的构造函数必须显式初始化基类