def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
def my_greeting(*fname):
print(fname + " Smith")
my_greeting("Don")
第一部分运行良好,第二部分崩溃。这是结果。
Emil Refsnes
Tobias Refsnes
Linus Refsnes
Traceback (most recent call last):
File "C:/Data/Python/turtleFun/kikiFunction.py", line 19, in <module>
my_greeting("Don")
File "C:/Data/Python/turtleFun/kikiFunction.py", line 17, in my_greeting
print(fname + " Smith")
TypeError: can only concatenate tuple (not "str") to tuple
我还没有创建元组,我没有尝试连接。结构相同,但一个运行,另一个崩溃。为什么 Python 3.8.3 认为我有一个元组?我该如何修复?元组将是
myTuple = ("Don", "Fred", "George", "Paul", "John", "Ringo")
最佳答案
问题
*fname
旁边的 *
始终使 fname
成为一个元组。
了解发生了什么
让我们看看以 *fname
作为参数的函数到底能做什么。
>>> def func(*fnames):
... print(fnames)
... print(type(fnames))
>>> func('str 1', 'str 2')
('str 1', 'str 2')
<class 'tuple'>
看看那个!尽管看起来像func
只需要1个参数(*fnames
),但当我们用2个参数调用它时,我们也不会收到错误参数('str 1'
和 'str 2'
)。这是因为 *fnames
中的 *
允许将任意数量的参数(包括 0!)传递给 func
,并且所有这些参数作为 1 个元组传入。
这就是为什么,即使您只向函数传递 1 个参数,fnames
仍然采用 tuple
类型。在您的示例中:
def my_greeting(*fname):
print(fname) # let's not concatenate for now
my_greeting('Don') # prints a tuple: ('Don',)
当 *fnames
被赋予 2 个以上参数时,为什么 Python 不只使用元组?
Python 始终使用元组作为 *
类型参数,以便我们的代码始终可以期望某种类型。否则,my_greeting('Don')
会将 fnames
设置为 str
,而 my_greeting('Don', 'Don2')
会将 fnames
设置为 str
的 tuple
。
希望这对您的学习有所帮助!
关于python - 为什么Python认为这是一个元组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62214361/