简体   繁体   English

我可以在 Python 中使用变量名“type”作为函数参数吗?

[英]Can I use the variable name “type” as function argument in Python?

Can I use type as a name for a python function argument?我可以使用type作为 python 函数参数的名称吗?

def fun(name, type):
    ....

You can, but you shouldn't.你可以,但你不应该。 It's not a good habit to use names of built-ins because they will override the name of the built-in in that scope.使用内置函数的名称不是一个好习惯,因为它们会覆盖该范围内的内置函数的名称。 If you must use that word, modify it slightly for the given context.如果您必须使用该词,请针对给定的上下文稍微修改它。

While it probably won't matter for a small project that is not using type , it's better to stay out of the habit of using the names of keywords/built-ins.虽然对于不使用type的小项目来说可能无关紧要,但最好不要养成使用关键字/内置函数名称的习惯。 The Python Style Guide provides a solution for this if you absolutely must use a name that conflicts with a keyword:如果您绝对必须使用与关键字冲突的名称,则Python 样式指南为此提供了解决方案:

single_trailing_underscore_ : used by convention to avoid conflicts with Python keyword, eg single_trailing_underscore_ :按照惯例使用以避免与 Python 关键字冲突,例如

Tkinter.Toplevel(master, class_='ClassName')

You can, and that's fine.你可以,这很好。 Even though the advice not to shadow builtins is important, it applies more strongly if an identifier is common, as it will increase confusion and collision.尽管不要隐藏内置函数的建议很重要,但如果标识符是通用的,它会更有效,因为它会增加混淆和冲突。 It does not appear type will cause confusion here (but you'll know about that more than anyone else), and I could use exactly what you have.看起来type不会在这里引起混淆(但你会比其他人更了解这一点),我可以完全使用你所拥有的。

You can use any non-keyword as an identifier (as long as it's a valid identifier of course).您可以使用任何非关键字作为标识符(当然,只要它是有效的标识符)。 type is not a keyword, but using it will shadow the type built-in. type不是关键字,但使用它会影响内置type

You can, but you would be masking the built-in name type.你可以,但你会屏蔽内置的名称类型。 So it's better not to do that.所以最好不要这样做。

You can use _type for that.您可以为此使用_type For example:例如:

def foo(_type):
    pass

If you use type , you can't use type() in that function.如果使用type ,则不能在该函数中使用type() For example:例如:

>>> type('foo')
<type 'str'>
>>> type = 'bar'
>>> type('foo')
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: 'str' object is not callable

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM