是否有将属性应用于 class 的迭代方法?

Is there an iterative method to apply attributes to a class?

假设地说,假设一个人有这个 class:

class Person:
  def __init__(self, lastName, firstName, age,):
    self.lastName = lastName
    self.firstName = firstName
    self.age = age

添加其他属性,方法相同。但是,写 self.attribute = attribute 一段时间后会变得非常烦人,尤其是在需要十几个或更多属性的情况下,在更大的 class.

的情况下

有什么方法可以将变量名迭代地应用到属性上吗?也许通过设置循环并自动应用属性?

您可以在 __init__ 方法中包含任意逻辑,归根结底,它的功能。所以这样的事情没有问题

 class myclass:
      def __init__(self,attributes):
         for att in attributes: self.att = att

编辑:虽然这不是您想要的,但您可以尝试在初始化之后设置属性,如下所示

atts = dict(#att:value dictionary)
for att,val in atts: setattr(myclass,att,val)

使用 dataclasses 模块 - 它减少了制作 class

的单调乏味
>>> from dataclasses import dataclass
>>> @dataclass
... class F:
...     attr1: str
...     attr2: str
...     attr3: str
...     attr4: str
>>> f = F('x','y','z','a')
>>> f
F(attr1='x', attr2='y', attr3='z', attr4='a')
>>> f.attr1
'x'