Мои Конспекты
Главная | Обратная связь

...

Автомобили
Астрономия
Биология
География
Дом и сад
Другие языки
Другое
Информатика
История
Культура
Литература
Логика
Математика
Медицина
Металлургия
Механика
Образование
Охрана труда
Педагогика
Политика
Право
Психология
Религия
Риторика
Социология
Спорт
Строительство
Технология
Туризм
Физика
Философия
Финансы
Химия
Черчение
Экология
Экономика
Электроника

Pass by reference vs value





Помощь в ✍️ написании работы
Поможем с курсовой, контрольной, дипломной, рефератом, отчетом по практике, научно-исследовательской и любой другой работой

All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function. For example:

#!/usr/bin/python # Function definition is heredef changeme( mylist ): "This changes a passed list into this function" mylist.append([1,2,3,4]); print "Values inside the function: ", mylist return # Now you can call changeme functionmylist = [10,20,30];changeme( mylist );print "Values outside the function: ", mylist

Here we are maintaining reference of the passed object and appending values in the same object. So this would produce following result:

Values inside the function: [10, 20, 30, [1, 2, 3, 4]]Values outside the function: [10, 20, 30, [1, 2, 3, 4]]

There is one more example where argument is being passed by reference but inside the function, but the reference is being over-written.

#!/usr/bin/python # Function definition is heredef changeme( mylist ): "This changes a passed list into this function" mylist = [1,2,3,4]; # This would assig new reference in mylist print "Values inside the function: ", mylist return # Now you can call changeme functionmylist = [10,20,30];changeme( mylist );print "Values outside the function: ", mylist

The parameter mylist is local to the function changeme. Changing mylist within the function does not affect mylist. The function accomplishes nothing and finally this would produce following result:

Values inside the function: [1, 2, 3, 4]Values outside the function: [10, 20, 30]

_____________________________________________________________________________

Function Arguments:

You can call a function by using the following types of formal arguments::

  • Required arguments
  • Keyword arguments
  • Default arguments
  • Variable-length arguments

Required arguments:

Required arguments are the arguments passed to a function in correct positional order. Here the number of arguments in the function call should match exactly with the function definition.

To call the function printme() you definitely need to pass one argument otherwise it would give a syntax error as follows:

#!/usr/bin/python # Function definition is heredef printme( str ): "This prints a passed string into this function" print str; return; # Now you can call printme functionprintme();

This would produce following result:

Traceback (most recent call last): File "test.py", line 11, in <module> printme();TypeError: printme() takes exactly 1 argument (0 given)

Keyword arguments:

Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name.

This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters.

You can also make keyword calls to the printme() function in the following ways:

#!/usr/bin/python # Function definition is heredef printme( str ): "This prints a passed string into this function" print str; return; # Now you can call printme functionprintme( str = "My string");

This would produce following result:

My string

Following example gives more clear picture. Note, here order of the parameter does not matter:

#!/usr/bin/python # Function definition is heredef printinfo( name, age ): "This prints a passed info into this function" print "Name: ", name; print "Age ", age; return; # Now you can call printinfo functionprintinfo( age=50, name="miki" );

This would produce following result:

Name: mikiAge 50

Default arguments:

A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument.

Following example gives idea on default arguments, it would print default age if it is not passed:

#!/usr/bin/python # Function definition is heredef printinfo( name, age = 35 ): "This prints a passed info into this function" print "Name: ", name; print "Age ", age; return; # Now you can call printinfo functionprintinfo( age=50, name="miki" );printinfo( name="miki" );

This would produce following result:

Name: mikiAge 50Name: mikiAge 35

Variable-length arguments:

You may need to process a function for more arguments than you specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments.

The general syntax for a function with non-keyword variable arguments is this:

def functionname([formal_args,] *var_args_tuple ): "function_docstring" function_suite return [expression]

An asterisk (*) is placed before the variable name that will hold the values of all nonkeyword variable arguments. This tuple remains empty if no additional arguments are specified during the function call. For example:

#!/usr/bin/python # Function definition is heredef printinfo( arg1, *vartuple ): "This prints a variable passed arguments" print "Output is: " print arg1 for var in vartuple: print var return; # Now you can call printinfo functionprintinfo( 10 );printinfo( 70, 60, 50 );

This would produce following result:

Output is:10Output is:706050

_____________________________________________________________________________

The Anonymous Functions:

You can use the lambda keyword to create small anonymous functions. These functions are called anonymous because they are not declared in the standard manner by using the def keyword.

· Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions.

· An anonymous function cannot be a direct call to print because lambda requires an expression.

· Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace.

· Although it appears that lambda's are a one-line version of a function, they are not equivalent to inline statements in C or C++, whose purpose is by passing function stack allocation during invocation for performance reasons.

Syntax:

The syntax of lambda functions contains only a single statement, which is as follows:

lambda [arg1 [,arg2,.....argn]]:expression

Example:

Following is the example to show how lembda form of function works:

#!/usr/bin/python # Function definition is heresum = lambda arg1, arg2: arg1 + arg2; # Now you can call sum as a functionprint "Value of total : ", sum( 10, 20 )print "Value of total : ", sum( 20, 20 )

This would produce following result:

Value of total : 30Value of total : 40

_____________________________________________________________________________

The return Statement:

The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None

All the above examples are not returning any value, but if you like you can return a value from a function as follows:

#!/usr/bin/python # Function definition is heredef sum( arg1, arg2 ): # Add both the parameters and return them." total = arg1 + arg2 print "Inside the function : ", total return total; # Now you can call sum functiontotal = sum( 10, 20 );print "Outside the function : ", total

This would produce following result:

Inside the function : 30Outside the function : 30

_____________________________________________________________________________

Scope of Variables:

All variables in a program may not be accessible at all locations in that program. This depends on where you have declared a variable.

The scope of a variable determines the portion of the program where you can access a particular identifier. There are two basic scopes of variables in Python:

  • Global variables
  • Local variables

Global vs. Local variables:

Variables that are defined inside a function body have a local scope, and those defined outside have a global scope.

This means that local variables can be accessed only inside the function in which they are declared whereas global variables can be accessed throughout the program body by all functions. When you call a function, the variables declared inside it are brought into scope.

Example:

#!/usr/bin/python total = 0; # This is global variable.# Function definition is heredef sum( arg1, arg2 ): # Add both the parameters and return them." total = arg1 + arg2; # Here total is local variable. print "Inside the function local total : ", total return total; # Now you can call sum functionsum( 10, 20 );print "Outside the function global total : ", total

This would produce following result:

Inside the function local total : 30Outside the function global total : 0

_____________________________________________________________________________

Python - Modules

A module allows you to logically organize your Python code. Grouping related code into a module makes the code easier to understand and use.

A module is a Python object with arbitrarily named attributes that you can bind and reference.

Simply, a module is a file consisting of Python code. A module can define functions, classes, and variables. A module can also include runnable code.

Example:

The Python code for a module named aname normally resides in a file named aname.py. Here's an example of a simple module, hello.py

def print_func( par ): print "Hello : ", par return

_____________________________________________________________________________

The import Statement:

You can use any Python source file as a module by executing an import statement in some other Python source file. import has the following syntax:

import module1[, module2[,... moduleN]

When the interpreter encounters an import statement, it imports the module if the module is present in the search path. Asearch path is a list of directories that the interpreter searches before importing a module.

Example:

To import the module hello.py, you need to put the following command at the top of the script:

#!/usr/bin/python # Import module helloimport hello # Now you can call defined function that module as followshello.print_func("Zara")

This would produce following result:

Hello : Zara

A module is loaded only once, regardless of the number of times it is imported. This prevents the module execution from happening over and over again if multiple imports occur.

_____________________________________________________________________________

The from...import Statement

Python's from statement lets you import specific attributes from a module into the current namespace:

Syntax:

from modname import name1[, name2[, ... nameN]]

Example:

For example, to import the function fibonacci from the module fib, use the following statement:

from fib import fibonacci

This statement does not import the entire module fib into the current namespace; it just introduces the item fibonacci from the module fib into the global symbol table of the importing module.

The from...import * Statement:

It is also possible to import all names from a module into the current namespace by using the following import statement:

from modname import *

This provides an easy way to import all the items from a module into the current namespace; however, this statement should be used sparingly.

Locating Modules:

When you import a module, the Python interpreter searches for the module in the following sequences:

· The current directory.

· If the module isn't found, Python then searches each directory in the shell variable PYTHONPATH.

· If all else fails, Python checks the default path. On UNIX, this default path is normally /usr/local/lib/python/.

The module search path is stored in the system module sys as the sys.path variable. The sys.path variable contains the current directory, PYTHONPATH, and the installation-dependent default.

_____________________________________________________________________________

The PYTHONPATH Variable:

The PYTHONPATH is an environment variable, consisting of a list of directories. The syntax of PYTHONPATH is the same as that of the shell variable PATH.

Here is a typical PYTHONPATH from a Windows system:

set PYTHONPATH=c:\python20\lib;

And here is a typical PYTHONPATH from a UNIX system:

set PYTHONPATH=/usr/local/lib/python

_____________________________________________________________________________

Namespaces and Scoping:

Variables are names (identifiers) that map to objects. A namespace is a dictionary of variable names (keys) and their corresponding objects (values).

A Python statement can access variables in a local namespace and in the global namespace. If a local and a global variable have the same name, the local variable shadows the global variable.

Each function has its own local namespace. Class methods follow the same scoping rule as ordinary functions.

Python makes educated guesses on whether variables are local or global. It assumes that any variable assigned a value in a function is local.

Therefore, in order to assign a value to a global variable within a function, you must first use the global statement.

The statement global VarName tells Python that VarName is a global variable. Python stops searching the local namespace for the variable.

For example, we define a variable Money in the global namespace. Within the function Money, we assign Money a value . therefor Python assumes Money is a local variable. However, we access the value of the local variable Money before setting it, so an UnboundLocalError is the result. Uncommenting the global statement fixes the problem.

#!/usr/bin/python   Money = 2000 def AddMoney(): # Uncomment the following line to fix the code: # global Money Money = Money + 1   print Money AddMoney() print Money

_____________________________________________________________________________

The dir( ) Function:

The dir() built-in function returns a sorted list of strings containing the names defined by a module.

The list contains the names of all the modules, variables, and functions that are defined in a module.

Example:

#!/usr/bin/python # Import built-in module mathimport math content = dir(math) print content;

This would produce following result:

['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log','log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh']

Here the special string variable __name__ is the module's name, and __file__ is the filename from which the module was loaded.

_____________________________________________________________________________

The globals() and locals() Functions:

The globals() and locals() functions can be used to return the names in the global and local namespaces depending on the location from where they are called.

If locals() is called from within a function, it will return all the names that can be accessed locally from that function.

If globals() is called from within a function, it will return all the names that can be accessed globally from that function.

The return type of both these functions is dictionary. Therefore, names can be extracted using the keys() function.

 

_____________________________________________________________________________

The reload() Function:

When the module is imported into a script, the code in the top-level portion of a module is executed only once.

Therefore, if you want to reexecute the top-level code in a module, you can use the reload() function. The reload() function imports a previously imported module again.

Syntax:

The syntax of the reload() function is this:

reload(module_name)

Here module_name is the name of the module you want to reload and not the string containing the module name. For example to re-load hello module, do the following:

reload(hello)

_____________________________________________________________________________

Packages in Python:

A package is a hierarchical file directory structure that defines a single Python application environment that consists of modules and subpackages and sub-subpackages, and so on.

Example:

Consider a file Pots.py available in Phone directory. This file has following line of source code:

#!/usr/bin/python def Pots(): print "I'm Pots Phone"

Similar way we have another two files having different functions with the same name as above:

  • Phone/Isdn.py file having function Isdn()
  • Phone/G3.py file having function G3()

Now create one more file __init__.py in Phone directory :

  • Phone/__init__.py

To make all of your functions available when you've imported Phone, you need to put explicit import statements in __init__.py as follows:

from Pots import Potsfrom Isdn import Isdnfrom G3 import G3

After you've added these lines to __init__.py, you have all of these classes available when you've imported the Phone package:

#!/usr/bin/python # Now import your Phone Package.import Phone Phone.Pots()Phone.Isdn()Phone.G3()

This would produce following result:

I'm Pots PhoneI'm 3G PhoneI'm ISDN Phone

Note: In the above example, we have taken example of a single functions in each file, but you can keep multiple functions in your files. You can also define different Python classes in those files and then you can create your packages out of those classes.

_____________________________________________________________________________

Printing to the Screen:

The simplest way to produce output is using the print statement where you can pass zero or more expressions, separated by commas. This function converts the expressions you pass it to a string and writes the result to standard output as follows:

#!/usr/bin/python print "Python is really a great language,", "isn't it?";

This would produce following result on your standard screen:

Python is really a great language, isn't it?

_____________________________________________________________________________

Reading Keyboard Input:

Python provides two built-in functions to read a line of text from standard input, which by default comes from the keyboard. These functions are:

· raw_input

· input

The raw_input Function:

The raw_input([prompt]) function reads one line from standard input and returns it as a string (removing the trailing newline):

#!/usr/bin/python str = raw_input("Enter your input: ");print "Received input is : ", str

This would prompt you to enter any string and it would display same string on the screen. When I typed "Hello Python!", it output is like this:

Enter your input: Hello PythonReceived input is : Hello Python

The input Function:

The input([prompt]) function is equivalent to raw_input, except that it assumes the input is a valid Python expression and returns the evaluated result to you:

#!/usr/bin/python str = input("Enter your input: ");print "Received input is : ", str

This would produce following result against the entered input:

Enter your input: [x*5 for x in range(2,10,2)]Recieved input is : [10, 20, 30, 40]

_____________________________________________________________________________

The open Function:

Before you can read or write a file, you have to open it using Python's built-in open() function. This function creates a file object which would be utilized to call other support methods associated with it.

Syntax:

file object = open(file_name [, access_mode][, buffering])

Here is paramters detail:

· file_name: The file_name argument is a string value that contains the name of the file that you want to access.

· access_mode: The access_mode determines the mode in which the file has to be opened ie. read, write append etc. A complete list of possible values is given below in the table. This is optional parameter and the default file access mode is read (r)

· buffering: If the buffering value is set to 0, no buffering will take place. If the buffering value is 1, line buffering will be performed while accessing a file. If you specify the buffering value as an integer greater than 1, then buffering action will be performed with the indicated buffer size. If negative, the buffer size is the system default(default behavior).

· Here is a list of the different modes of opening a file:

Modes Description
r Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.
rb Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode.
r+ Opens a file for both reading and writing. The file pointer will be at the beginning of the file.
rb+ Opens a file for both reading and writing in binary format. The file pointer will be at the beginning of the file.
w Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
wb Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
w+ Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
wb+ Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
a Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
ab Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
a+ Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.
ab+ Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

_____________________________________________________________________________

The file object atrributes:

Once a file is opened and you have one file object, you can get various information related to that file.

Here is a list of all attributes related to file object:

Attribute Description
file.closed Returns true if file is closed, false otherwise.
file.mode Returns access mode with which file was opened.
file.name Returns name of the file.
file.softspace Returns false if space explicitly required with print, true otherwise.

Example:

#!/usr/bin/python # Open a filefo = open("foo.txt", "wb")print "Name of the file: ", fo.nameprint "Closed or not : ", fo.closedprint "Opening mode : ", fo.modeprint "Softspace flag : ", fo.softspace

This would produce following result:

Name of the file: foo.txtClosed or not : FalseOpening mode : wbSoftspace flag : 0

_____________________________________________________________________________

The close() Method:

The close() method of a file object flushes any unwritten information and closes the file object, after which no more writing can be done.

Python automatically closes a file when the reference object of a file is reassigned to another file. It is a good practice to use the close() method to close a file.

Syntax:

fileObject.close();

Example:

#!/usr/bin/python # Open a filefo = open("foo.txt", "wb")print "Name of the file: ", fo.name # Close opend filefo.close()

This would produce following result:

Name of the file: foo.txt

_____________________________________________________________________________

Reading and Writing Files:

The file object provides a set of access methods to make our lives easier. We would see how to use read() and write() methods to read and write files.

The write() Method:

The write() method writes any string to an open file. It is important to note that Python strings can have binary data and not just text.

The write() method does not add a newline character ('\n') to the end of the string:

Syntax:

fileObject.write(string);

Here passed parameter is the content to be written into the opend file.

Example:

#!/usr/bin/python # Open a filefo = open("foo.txt", "wb")fo.write( "Python is a great language.\nYeah its great!!\n"); # Close opend filefo.close()

The above method would create foo.txt file and would write given content in that file and finally it would close that file. If you would open this file, it would have following content

Python is a great language.Yeah its great!!

The read() Method:

The read() method read a string from an open file. It is important to note that Python strings can have binary data and not just text.

Syntax:

fileObject.read([count]);

Here passed parameter is the number of bytes to be read from the opend file. This method starts reading from the beginning of the file and if count is missing then it tries to read as much as possible, may be until the end of file.

Example:

Let's take a file foo.txt which we have created above.

#!/usr/bin/python # Open a filefo = open("foo.txt", "r+")str = fo.read(10);print "Read String is : ", str# Close opend filefo.close()

This would produce following result:

Read String is : Python is

_____________________________________________________________________________

File Positions:

The tell() method tells you the current position within the file in other words, the next read or write will occur at that many bytes from the beginning of the file:

The seek(offset[, from]) method changes the current file position. The offset argument indicates the number of bytes to be moved. The from argument specifies the reference position from where the bytes are to be moved.

If from is set to 0, it means use the beginning of the file as the reference position and 1 means use the current position as the reference position and if it is set to 2 then the end of the file would be taken as the reference position.

Example:

Let's take a file foo.txt which we have created above.

#!/usr/bin/python # Open a filefo = open("foo.txt", "r+")str = fo.read(10);print "Read String is : ", str # Check current positionposition = fo.tell();print "Current file position : ", position # Reposition pointer at the beginning once againposition = fo.seek(0, 0);str = fo.read(10);print "Again read String is : ", str# Close opend filefo.close()

This would produce following result:

Read String is : Python isCurrent file position : 10Again read String is : Python is

_____________________________________________________________________________

Renaming and Deleting Files:

Python os module provides methods that help you perform file-processing operations, such as renaming and deleting files.

To use this module you need to import it first and then you can all any related functions.

The rename() Method:

The rename() method takes two arguments, the current filename and the new filename.

Syntax:

os.rename(current_file_name, new_file_name)

Example:

Following is the example to rename an existing file test1.txt:

#!/usr/bin/pythonimport os # Rename a file from test1.txt to test2.txtos.rename( "test1.txt", "test2.txt" )

The delete() Method:

You can use the delete() method to delete files by supplying the name of the file to be deleted as the argument.

Syntax:

os.delete(file_name)

Example:

Following is the example to delete an existing file test2.txt:

#!/usr/bin/pythonimport os # Delete file test2.txtos.delete("text2.txt")

_____________________________________________________________________________

Directories in Python:

All files are contained within various directories, and Python has no problem handling these too. The os module has several methods that help you create, remove, and change directories.

The mkdir() Method:

You can use the mkdir() method of the os module to create directories in the current directory. You need to supply an argument to this method, which contains the name of the directory to be created.

Syntax:

os.mkdir("newdir")

Example:

Following is the example to create a directory test in the current directory:

#!/usr/bin/pythonimport os # Create a directory "test"os.mkdir("test")

The chdir() Method:

You can use the chdir() method to change the current directory. The chdir() method takes an argument, which is the name of the directory that you want to make the current directory.

Syntax:

os.chdir("newdir")

Example:

Following is the example to go into "/home/newdir" directory:

#!/usr/bin/pythonimport os # Changing a directory to "/home/newdir"os.chdir("/home/newdir")

The getcwd() Method:

The getcwd() method displays the current working directory.

Syntax:

os.getcwd()

Example:

Following is the example to give current directory:

#!/usr/bin/pythonimport os # This would give location of the current directoryos.getcwd()

The rmdir() Method:

The rmdir() method deletes the directory, which is passed as an argument in the method.

Before removing a directory, all the contents in it should be removed.

Syntax:

os.rmdir('dirname')

Example:

Following is the example to remove "/tmp/test" directory. It is required to give fully qualified name of the directory otherwise it would search for that directory in the current directory.

#!/usr/bin/pythonimport os # This would remove "/tmp/test" directory.os.rmdir( "/tmp/test" )

File & Directory Related Methods:

There are three important sources which provide a wide range of utility methods to handle and manipulate files & directories on Windows and Unix operating systems. They are as follows:

· File Object Methods: The file object provides functions to manipulate files.

· OS Object Methods.: This provides methods to process files as well as directories.

_____________________________________________________________________________

Доверь свою работу ✍️ кандидату наук!
Поможем с курсовой, контрольной, дипломной, рефератом, отчетом по практике, научно-исследовательской и любой другой работой



Поиск по сайту:







©2015-2020 mykonspekts.ru Все права принадлежат авторам размещенных материалов.