简体   繁体   中英

Calling a function in Python - no class specified?

I noticed that some functions, for example sorted , can be called without specifying the instance they belong to - just like some function f I would define in my own class and won't need to specify that I'm calling them from my class.

Where do these functions belong and how does this hierarchy work?

In Python everything is an object. But you don't need to specify classes to everything. Some objects have their types (classes) hard-defined in the language core - that is the case for functions, integers, float, lists, dictionaries, strings and the like

So, whether you define a function inside a module or use a native function from some 3rd party package or from the builtins module, the function's type is "FunctionType" - which never needs to be declared explicitly.

And more related with your doubt: functions do not need to be related to any class - they are objects on their own, and the syntax of adding an optional list of arguments enclosed in mandatory parenthesis after their name calls them.

So just like C, Javascript, etc... you can create very complexes programs in Python with never defining a class.

Functions defined inside class bodies, on the other hand, are used as methods when retrieved through an instance of that class (or through the class if they are classmethods). That is Python 3 - Python 2 would be more complicated: functions defined inside a class body retrieved though the class itself are "unbound methods" - another object type.

And finally, the is a special module in Python called __builtins__ , which is populated by the Python runtime itself. Any name you try to use in a section of code is checked to be in one of these contexts: local context, nonlocal (outer closure for nested functions), global (variables, functions and classes defined at module level), or builtin (it is present in the __builtins__ module).

There are a few functions and several classes defined in __builtins__ which allow one to write fairly complete Python code without the need for any imports:

>>> 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', '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']

So, what you type in a Python module is either a statement, one of the names above, or have to be declared prior to be used in some form (with an = statement, or though the use of import , or even a function with the def statement).

As a final advice, since you are learning Python you probably don't have a legacy codebase in Python 2 around there: you should be learning Python 3. It makes a lot of things simpler, and contains more than 9 years of innovations over Python 2, which will cease to be maintained 2 years from now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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