有没有办法创建一个类实例,并将属性列表传递给构造函数?
假设我有这个类,
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需使用 iterable-unpacking 将参数列表作为顺序位置参数传递即可:
调用中
attributes
前面的*
表示:attributes
是一个可迭代的,self
之后),第二个元素成为第二个位置参数,等等attributes
中提取的元素数量与Foo
期望的参数计数相匹配(因为Foo
除了self
之外还采用了三个参数,属性
必须生成恰好三个参数,不多也不少)Just use iterable-unpacking to pass your
list
of arguments as sequential positional arguments:The
*
in front ofattributes
in the call means:attributes
is an iterableself
), the second element the second positional argument, etc.attributes
matches the argument count expected byFoo
(sinceFoo
takes three arguments beyondself
,attributes
must produce exactly three arguments, no more, no less)