如何在 Python 构造函数中使用 *args 和 self
How to use *args and self in Python constructor
我需要一个 Python 方法来访问 self 作为实例变量,并且还能够接受任意数量的参数。我基本上想要一个可以通过
调用的方法 foo
foo(a, b, c)
或
foo()
在class中,我认为构造函数是
def foo(self, *args):
这是正确的吗?另外,仅供参考,我是 Python 的新手(如果你不知道的话)。
def foo(self, *args):
是的,没错。
你只需要在self
参数后面加上:
class YourClass:
def foo(self, *args):
print(args)
def bar(self, *args, **kwargs):
print(args)
print(kwargs)
def baz(self, **kwargs):
print(kwargs)
我还添加了一种方法,您还可以在其中添加 **kwargs
,以及同时添加 *args
和 **kwargs
的情况。
例子
>>> o = YourClass()
>>> o.foo()
()
>>> o.foo(1)
(1,)
>>> o.foo(1, 2)
(1, 2)
您正确地声明了该方法。您还可以使用双星号来接受关键字参数。
Reference: Expressions
A double asterisk ** denotes dictionary unpacking. Its operand must be a mapping. Each mapping item is added to the new dictionary. Later values replace values already set by earlier key/datum pairs and earlier dictionary unpackings.
....
An asterisk * denotes iterable unpacking. Its operand must be an iterable. The iterable is expanded into a sequence of items, which are included in the new tuple, list, or set, at the site of the unpacking.
Args 将是一个元组。要访问这些值,您必须迭代或使用位置参数,即:args[0]
我需要一个 Python 方法来访问 self 作为实例变量,并且还能够接受任意数量的参数。我基本上想要一个可以通过
调用的方法 foofoo(a, b, c)
或
foo()
在class中,我认为构造函数是
def foo(self, *args):
这是正确的吗?另外,仅供参考,我是 Python 的新手(如果你不知道的话)。
def foo(self, *args):
是的,没错。
你只需要在self
参数后面加上:
class YourClass:
def foo(self, *args):
print(args)
def bar(self, *args, **kwargs):
print(args)
print(kwargs)
def baz(self, **kwargs):
print(kwargs)
我还添加了一种方法,您还可以在其中添加 **kwargs
,以及同时添加 *args
和 **kwargs
的情况。
例子
>>> o = YourClass()
>>> o.foo()
()
>>> o.foo(1)
(1,)
>>> o.foo(1, 2)
(1, 2)
您正确地声明了该方法。您还可以使用双星号来接受关键字参数。 Reference: Expressions
A double asterisk ** denotes dictionary unpacking. Its operand must be a mapping. Each mapping item is added to the new dictionary. Later values replace values already set by earlier key/datum pairs and earlier dictionary unpackings.
....
An asterisk * denotes iterable unpacking. Its operand must be an iterable. The iterable is expanded into a sequence of items, which are included in the new tuple, list, or set, at the site of the unpacking.
Args 将是一个元组。要访问这些值,您必须迭代或使用位置参数,即:args[0]