龙空技术网

Python之旅-标识符

程序猿独钓江月 91

前言:

现时大家对“python关键字as”可能比较关怀,我们都想要知道一些“python关键字as”的相关知识。那么小编在网上网罗了一些对于“python关键字as””的相关文章,希望姐妹们能喜欢,大家一起来了解一下吧!

标识符是任可一种编程语言的基础,就像每个人都有名字一样,起名有规则,Python也一样对标识符命名有一定的规则。

Python标识符是由1个引导字符+0个或多个后续字符组成任意长度的非空字符序列,并有明确的规则与约定。

引导字符引导字符可以是Unicode编码中的字母和下划线,其中字母不局限于ASCII字母(‘a’..’z’,’A’..’Z’),还包括非英文语言的字母。后续字符后续字符除了可以是引导字符规定的字符外,还可以是Unicode编码中认为是数字的字符。大小写敏感Python标识符是大小写敏感的,如Python、python、PYthon表示的是不同的标识符。标识符不能与Python关键字同名Python关键字如下(目前33个):and, as, assertbreakclass, continuedef, delelif, else, exceptFalse, finally, for, fromglobalif, import, in, islambdaNone, nonlocal, notorpassraise, returnTrue, trywhile, withyield不要使用Python预定义的标识符进行自定义标识符命名Python预定义的标识符都有特定的含义,如果你用些预定义的标识符作为变量重新定义,那将改变原来的意义,主要包括内置的异常名、函数名、数据类型等,在Python环境下输入dir()将得到Python内置属性列表,如:dir()['AttributeError', 'Ellipsis', 'NotImplemented', '__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'int']dir(属性值)可以看到更详细的属性列表,如dir(__builtins__)['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EncodingWarning', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '_', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'aiter', 'all', 'anext', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']这些Python预定义的标识符都不应作为自定义的标识符来命名,我们来下面的例子就明白这是为什么了,

>>>int

<class 'int'>

>>>x = int(5)

>>>x

5

>>>int = 9

>>>int

9

>>>y = int(5)

Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'int' object is not callable

int是预定义的内置数据类型,直接输入int返回<class ‘int’>表明它是int类型,此时x = int(5),意思是把5通过类型转换赋值给变量x, 这是没问题了,接下来,int = 9,这里全用标识符int作为变量名进行了自定义并赋值9,再输入int,得到的是数值9,而不再是<class ‘int’>,也就是说int再再是整型数据类型了,如果再当作数据类型来调用(y = int(5)),那就会出现异常。避免使用开头各结尾都是下划线的标识符名虽然它可能也是有效的标识符,但是还是建议避免使用,因为Pyhon定义了各种特殊的方法和变量,使用的就是这种命名规则,如果我们再使用这样的自定义标识符很容易造成混淆。单个下划线(_)也有个有效的标识符在Python交互环境中输入单个下划线,它返回的是最后一个被评估的表达式的结果,但在程序中它就是一个字符,常用在不关心数据项的for…in循环中,如:for _ in range(10):print(’————’)

判断一个字符串是否是有效标识符最简单的办法就是在Python交互环境中作为变量给它赋值,如果没有异常则说明它是有效的标识符,如果是无效的标识符就会产生SyntaxError异常,当然有效的标识符并不代表在我们的程序中使用它,记住上面提到的几个要点。

常用的标识符命名习惯模块名首字母大写,如 Mypub.py自定义类名用大驼峰法命名,每词首字母大写,如 NanNing常量名全大写,如 LISTCASE变量名用小驼峰命名法,第一个词首字母小写,后面每个词着字母大写,如 isHideWindows方法及函数名全部小写,每词间用下划线连接,如 index_of_list()

标签: #python关键字as #未定义标识符 #python中的标识符