为什么在Python 3中,*args的结果以空列表开头?
我正在学习Python,以前从未使用过任意数参数函数,我很难理解为什么我得到了我得到的。具体来说,我正在运行以下代码:为什么在Python 3中,*args的结果以空列表开头?,python,python-3.x,Python,Python 3.x,我正在学习Python,以前从未使用过任意数参数函数,我很难理解为什么我得到了我得到的。具体来说,我正在运行以下代码: class LocationList(list): def __init__(*pargs): print(pargs) print(len(pargs)) for the_item in pargs: print(the_item) the_location = LocationList('a
class LocationList(list):
def __init__(*pargs):
print(pargs)
print(len(pargs))
for the_item in pargs:
print(the_item)
the_location = LocationList('a location', 'another location')
我得到的是:
([], 'a location', 'another location')
3
[]
a location
another location
为什么一开始我就得到了空名单
我在Linux下使用Python 3.4.3。因为方法的第一个参数是调用它的对象。并且该对象是
列表
的后代。空列表打印为“[]”,因为方法的第一个参数是调用它的对象。并且该对象是列表
的后代。空列表打印为“[]”*pargs,因为它的前缀是“*”(星号),将所有参数收集到一个元组中。此外,对于类和对象方法定义,第一个参数始终是“self”,在本例中,它是执行此操作时创建的对象(或实例):
the_location = LocationList('a location', 'another location')
此外,您的类正在扩展列表:
class LocationList(list):
因此,self(对象)成为一个列表:
([], 'a location', 'another location') # self == []
*由于pargs的前缀是“*”(一个星号),它将所有参数收集到一个元组中。此外,对于类和对象方法定义,第一个参数始终是“self”,在本例中,它是执行此操作时创建的对象(或实例):
the_location = LocationList('a location', 'another location')
此外,您的类正在扩展列表:
class LocationList(list):
因此,self(对象)成为一个列表:
([], 'a location', 'another location') # self == []
类中的方法将self作为第一个参数,包括
__init__()
为了得到我认为您想要的结果:
def __init__(self, *pargs):
...
类中的方法将self作为第一个参数,包括
__init__()
为了得到我认为您想要的结果:
def __init__(self, *pargs):
...
这是
self
参数。它显示为列表,因为您从列表继承,继承它的\uuuu str\uuuu
和\uuuu repr\uuu
方法。它是self
参数。它显示为列表,因为您从列表继承,继承其\u str\u
和\u repr\u
方法。