2016-07-14 5 views
1

Ich las Python tutorial und kam in dieser Linie, die ich nicht verstehen konnte:Was sind integrierte Bezeichner in Python?

Standard-Ausnahme-Namen sind eingebaute Bezeichner (nicht Schlüsselwörter reserviert).

Was ist mit built-in identifiers gemeint? Ich weiß, dass es eingebaute Funktionen wie open(), d.h. Funktionen gibt, die wir nicht importieren müssen.

+0

Die Standard Ausnahmen geben, sind Teil der ' '' builtin''''s ihre Namen sind nur Bezeichner, KEINE Schlüsselwörter. versuche '' 'import builtins; für den Bezeichner in dir (builtins): print (Bezeichner) '' '. Es sollte den Namen/Bezeichner für jede der * eingebauten * Ausnahmen plus andere eingebaute ausgeben. – wwii

Antwort

1

In Python, eine Kennung der Name zu einer bestimmten Einheit, sei es eine Klasse, Variable, Funktion usw. Zum Beispiel gegeben ist, wenn ich schreibe:

some_variable = 2 
try: 
    x = 6/(some_variable - 2) 
except ZeroDivisionError: 
    x = None 

beide some_variable und x sind Kennungen, die ich habe definiert. Die dritte Kennung ist hier die ZeroDivisionError Ausnahme, die eine eingebaute in Kennung ist (das heißt, Sie nicht importieren müssen oder sie definieren, bevor Sie es verwenden können).

Dies steht im Gegensatz zu reservierten Schlüsselwörtern, die kein Objekt identifizieren, sondern helfen, die Python-Sprache selbst zu definieren. Dazu gehören import, for, while, try, except, if, else, etc ...

1

Bezeichner sind 'Variablennamen'. Einbauten sind, gut, eingebaute Objekte, die mit Python kommen und nicht importiert werden müssen. Sie sind mit Identifizierern in der gleichen Weise verbunden, wie wir 5 mit foo assoziieren können, indem wir foo = 5 sagen.

Schlüsselwörter sind spezielle Token wie def. Bezeichner können keine Schlüsselwörter sein. Schlüsselwörter sind 'reserviert'.

Für integrierte Schlüsselwörter wie open können Sie jedoch Identifikatoren mit der gleichen Schreibweise verwenden. So können Sie sagen open = lambda: None und Sie haben die eingebaute zuvor mit dem Namen open verknüpfte oder 'überschattet'. Es ist im Allgemeinen keine gute Idee, Einbauten zu überschatten, da sie die Lesbarkeit erhöhen.

3

Es ist genau das, was Sie denken, es ist ein Name einer Sache, die nicht eine Funktion ist, und ist kein Befehl wie „while“ und kommt eingebaut in Python. z.B.

Eine Funktion ist so etwas wie open(), ist ein Schlüsselwort, so etwas wie while und ein Identifikator ist so etwas wie True oder IOError.

Mehr davon:

>>> dir(__builtins__) 
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 
'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'Ellipsis', 
'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 
'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 
'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 
'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 
'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 
'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 
'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 
'TabError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 
'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 
'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', 
'_', '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs', 
'all', 'any', 'apply', 'basestring', 'bin', 'bool', 'buffer', 'bytearray', 
'bytes', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 
'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 
'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float', 'format', 
'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 
'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license', 
'list', 'locals', 'long', 'map', 'max', 'memoryview', 'min', 'next', 'object', 
'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'raw_input', 
'reduce', 'reload', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 
'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 
'unicode', 'vars', 'xrange', 'zip'] 

Dokumentation Sicherung:

https://docs.python.org/2/reference/expressions.html

5,2. Atome Atome sind die grundlegendsten Elemente von Ausdrücken.Die einfachsten Atome sind Bezeichner oder Literale

Eine Kennung als ein Atom auftritt, ist ein Name

https://docs.python.org/2/reference/lexical_analysis.html#identifiers

Identifiers (auch als Namen bezeichnet)

0

Sie können erhalten alle Builtins, die folgenden Befehl verwenden ...

dir(__builtins__) 

es geben Ausgang folgende

>>> dir(__builtins__) 
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', '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', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', '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'] 

dann, wenn Sie überprüfen möchten, was können wir mit diesen builtins tun Nachfolgend erhalten Sie die Definition help("<name_of_the_builin_function>")

>>> help("zip") 
Help on class zip in module builtins: 

class zip(object) 
| zip(iter1 [,iter2 [...]]) --> zip object 
| 
| Return a zip object whose .__next__() method returns a tuple where 
| the i-th element comes from the i-th iterable argument. The .__next__() 
| method continues until the shortest iterable in the argument sequence 
| is exhausted and then it raises StopIteration. 
| 
| Methods defined here: 
| 
| __getattribute__(self, name, /) 
|  Return getattr(self, name). 
| 
| __iter__(self, /) 
|  Implement iter(self). 
| 
| __new__(*args, **kwargs) from builtins.type 
|  Create and return a new object. See help(type) for accurate signature. 
| 
| __next__(self, /) 
|  Implement next(self). 
| 
| __reduce__(...) 
|  Return state information for pickling. 
Verwandte Themen