

This is not true in other OOP languages like Java or C#. Therefore functions are called first-class citizens. They can be manipulated like other objects in Python. Functions are objectsįunctions in Python are objects. $ f() method f() function f() inner function Other functions are called using their names and square brackets. The static method is called by specifying the class name, the dot operator and the function name with square brackets. Here the f() function is defined inside another g() function. In this example, we define an f() function in all possible places.Ī static method is defined with a decorator in a Some class.ĭef g(): def f(): print "f() inner function" #!/usr/bin/python class def f(): print "f() method"ĭef g(): def f(): print "f() inner function" f() Function defined inside a class is called a method. Where to define functionsįunctions can be defined inside a module, a class or another function. Uncommenting the line we get a NameError. We can call the f2() only after its definition. Function call cannot be ahead of its definition. In the above example we have two definitions of functions. Otherwise the interpreter will complain with a NameError. author: Jan Bodnar ZetCode, 2011ĭefinitions of functions must precede their usage.
#Construct 3 advancd programming how to#
The script shows how to work with functions in Python. Note that there are two underscores on both sides of the attribute. The _doc_ and _file_ are special state attributes. If they explicitly do not return a value, they implicitly return None. The second will return the path of our module. The first function will print the module doc string.
#Construct 3 advancd programming code#
The file in which we put Python code is called a module. The string at the top of the script is called the documentation string. author: Jan BodnarĪ = showModuleName() b = getModuleFile() print a, b To call a function, we specify the function name with the round brackets. They are not executed until the function is called. If we call a function, the statements inside the function body are executed. The function is later executed when needed. The indented statements form a body of the function. The def keyword is followed by the function name with round brackets and a colon. The statements in the block of the function must be indented. Defining functionsĪ function is created with the def keyword. The user defined functions are functions created with the def keyword. The built-in functions are part of the Python language. Built-in functions and user defined ones. This brings additional flexibility to the language. Functions can be assigned to variables, stored in collections or passed as arguments. It means that functions have equal status with other objects in Python.
