有没有办法创建一个类实例,并将属性列表传递给构造函数?

发布于 2025-01-16 14:44:42 字数 327 浏览 1 评论 0原文

假设我有这个类,

class Foo:

    def __init__(self, a, b, c):
         self.a = a
         self.b = b
         self.c = c

有没有办法在构造函数参数中创建快捷方式,这样我就不需要显式传递列表中的每个参数,例如:

def main():
    attributes = [1,2,3]
    foo = Foo(attributes) #instead of Foo(attributes[0], ...., ....)

Let's say I have this class

class Foo:

    def __init__(self, a, b, c):
         self.a = a
         self.b = b
         self.c = c

Is there a way to make a shortcut in the constructor arguments so I don't need to explicitly pass every parameter from a list, for example:

def main():
    attributes = [1,2,3]
    foo = Foo(attributes) #instead of Foo(attributes[0], ...., ....)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

逆流 2025-01-23 14:44:42

只需使用 iterable-unpacking 将参数列表作为顺序位置参数传递即可:

def main():
    attributes = [1,2,3]
    foo = Foo(*attributes)

调用中 attributes 前面的 * 表示:

  1. attributes 是一个可迭代的,
  2. 它应该被解包,使得第一个元素成为第一个位置参数(在隐含的 self 之后),第二个元素成为第二个位置参数,等等
  3. 。断言该数字您可以从 attributes 中提取的元素数量与 Foo 期望的参数计数相匹配(因为 Foo 除了 self 之外还采用了三个参数,属性必须生成恰好三个参数,不多也不少)

Just use iterable-unpacking to pass your list of arguments as sequential positional arguments:

def main():
    attributes = [1,2,3]
    foo = Foo(*attributes)

The * in front of attributes in the call means:

  1. attributes is an iterable
  2. It should be unpacked such that the first element becomes the first positional argument (after the implied self), the second element the second positional argument, etc.
  3. You're making an assertion that the number of elements you can pull from attributes matches the argument count expected by Foo (since Foo takes three arguments beyond self, attributes must produce exactly three arguments, no more, no less)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文