根据 __init__ 个参数设置 __init__ 个属性

Set __init__ attributes based on __init__ arguments

我想减少 class 定义中的行数并创建 __init __ 个与 __init __ 个参数同名的属性。这可能吗?

class Num():
    def __init__(self, arg1, arg2):
        self.arg3 = 'three'
        # some magic here

a = Num('one', 'two')  # instance

然后

print(a.arg1)  # one
print(a.arg2)  # two
print(a.arg3)  # three

如果你想从参数列表中推断出来,你可以用 locals():

做一些棘手的事情
class Num:
    def __init__(self, arg1, arg2):
        for var, val in locals().items():
            if var != 'self':
                self.__setattr__(var, val)
        self.arg3 = "three"


a = Num('one', 'two')  # instance
print(a.arg1)  # one
print(a.arg2)  # two
print(a.arg3)  # three

更好的解决方案是使用数据类:

from dataclasses import dataclass


@dataclass
class Num:
    arg1: str
    arg2: str
    arg3: str = "three"


a = Num('one', 'two')  # instance
print(a.arg1)  # one
print(a.arg2)  # two
print(a.arg3)  # three