PYTHON

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

import *logging*

# *DEBUG*: Detailed information, typically of interest only when diagnosing problems # *INFO*: Confirmation that thins are working as expected # *WARNING*: An indication that something unexpected happened, or indicative of some problems in the near future (e.g., disk space low). The software is still working as expected. #*ERROR*: Due to a more serious problem, the software has not been able to perform some functions. #*CRITICAL*: A serious error, indicating that the problem itself may be unable to continue running.

Argument of an Exception An exception can have an argument, which is a value that gives additional information about the problem. The contents of the argument vary by exception.

# Define a function here. def temp_convert(var): try: return int(var) except ValueError, Argument: print "The argument does not contain numbers\n", Argument # Call above function here. temp_convert("xyz"); The argument does not contain numbers invalid literal for int() with base 10: 'xyz'

*Set comprehensions* Set is like a list except it has all unique values

# I want the set of the nums nums = [1,1,2,1,3,4,3,4,5,5,6,7,8,7,9,9] my_set = set() for n in nums: my_set.add(n) print my_set result >> set([1, 2, 3, 4, 5, 6, 7, 8, 9, ]) ========================== my_set = {n for n in nums} print my_set

*Generator expressions*

# I want to yield 'n*n' for each 'n' in nums nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] def gen_func(num): for n in nums: yield n*n my_gen = gen_func(nums) ========================== my_gen = (n*n for n in nums) for i in my_gen print i

*return* - takes the control back where the function was called.

# function definition is here def sum(arg1, arg2): total = arg1 + arg2 print("Inside function", total) return total # now lets call the function total = sum(10, 20) print("outside the function", total)

*List comprehensions*

# copy each element of nums in my_list nums = [1, 2, 3, 4, 5] my_list = [] for n in nums: my_list.append(n) print my_list ========================== my_list = [n for n in nums] print my_least +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # I want 'n*n' for each 'n' in nums my_list = [] for n in nums: my_list.append(n*n) print my_list ========================== my_list = [n*n for n in nums] print my_list +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # using a map + lambda my_list = map(lambda n: n*n, nums) print my_list +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #I want 'n' for each 'n' in nums if 'n' is even my_list = [] for n in nums: if n%2 == 0: my_list.append(n) print my_list ========================== my_list = [n for n nums if n%2 == 0] print my_list # using a filter + lambda my_list = filter(lambda n: n%2 == 0, nums) print my_list +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # I want a (letter, num) pair (list) for each letter in 'abcd' # and each number in '0123' my_list = [] for letter in 'abcd': for num in range(4): my_list.append((letter,num)) print my_list [('a',0), ('a',1) ...] ========================== my_list = [(letter,num) for letter in 'abcd' for num in range(4)]

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.

#!/usr/bin/python # Import built-in module math import math content = dir(math) print content ['__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']

*Padding(length, pattern=b'\x00', strict=False)*. \x00 = HEX 0

*:param length:* -- > the length of the field. the length can be either an integer, or a function that takes the context as an argument and returns the length *:param pattern:* -- > the padding pattern (character) to use. default is "\x00" *:param strict:* -- > whether or not to raise an exception is the actual padding pattern mismatches the desired pattern. default is False.

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. *KEYWORD ARGUMENTS* def printinfo( name, age ): # Now you can call printinfo function printinfo( age=50, name="miki" ) We can call the function also out of order. To do so, we have to use the same variable names that are used in the function definition. *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. def printinfo( name, age = 35 ): printinfo( age=50, name="miki" ) printinfo( name="miki" ) Name: miki Age 50 Name: miki Age 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. def functionname([formal_args,] *var_args_tuple ): The compulsory arguments are assigned to *formal_args* , while the variable ones to *var_args_tuple* tuple

All of pre-defined attributed can be overridden

*__init__(self [, args...])*: - Constructor (with any optional arguments) *__del__(self)*: - Destructor, deletes an object *__repr__(self)*: - Evaluates string representation *__str__(self)*: - Printable string representation *__cmp__(self,x)*: - Object comparison

*Array(count, subcon)* *Repeats the given unit a fixed number of times.* :param count: number of times to repeat :param subcon: construct to repeat c = Array(4, UBInt8("foo"))

*c.parse("\x01\x02\x03\x04") -- > [1, 2, 3, 4]* *c.build([5,6,7,8]) -- > '\x05\x06\x07\x08'*

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

*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, i.e., 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 takes place. If the buffering value is 1, line buffering is performed while accessing a file. If you specify the buffering value as an integer greater than 1, then buffering action is performed with the indicated buffer size. If negative, the buffer size is the system default(default behavior).

*nonlocal x* -- > affects the local variable of the enclosing function in nested functions

*global x* -- > affects the global variable from the a fucntion

IMPORT

*import module1[, module2[ , .....]* When the interpreter encounters an import statement, it imports the module if the module is present in the search path. A search path is a python directory that the python interpreter searches before importing a module Sometimes we need to import just a small part of a module. If we just use the small part then loading the entire module will unnecessarily load the program *from modnume import name1[, name2[,.. nemeN]* names-- could be functions in a module

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

*locals()* If locals() is called from within a function, it will return all the names that can be accessed locally from that function. The return type of both these functions is dictionary. Therefore, names can be extracted using the keys() function.

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

*os.rename(current_file_name, new_file_name)* *os.remove(file_name)* *os.mkdir("newdir")* *os.chdir("newdir")* *os.getcwd()* -- > display current working direct. *os.rmdir('dirname')

Generators over lists if my_nums in a generator and we want to convert to a list list(my_nums)

*yield* makes generator object Generators do not hold the entire result in the memory. It yields one result at a time def square_numbers(nums): for i in nums: yield(i*i) my_nums = square_numbers([1, 2, 3, 4, 5]) print next(my_num) print next(my_num) result -- > 1 result -- > 2 for num in my_nums: print num

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 searched each directory in the shell variable PYTHONPATH. - If all else fails, Python checks the default path. On UNIX, this is 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. PYTHONPATH can be a *.bash_profile*

*Class Inheritance* *lass DerivedClassName(modname.BaseClassName):*

- You create a class by deriving it from an existing class by listing the parent class in the parentheses after a new class name. - The child class inherits the attributes of its parent class, and you can use those attributes as if they were defined in the child class. - A child class can also override data members and methods from the parent - Derived classes are declared much like their parent class; however, a list of base classes to inherit from are given after class name class SubClassName (ParentClass1, ...): 'optional class documentation strin' class_suite When the class object is constructed, the base class is remembered. This is used for resolving attribute references: if a requested attribute is not found in the class, the search proceeds to look in the base class. This rule is applied recursively if the base class itself is derived from some other class.

*Container*

Containers are the common way to express parsed data.

LISTS object

A list contains items separated by commas and enclosed within square brackets ([]). To some extent, lists are similar to arrays in C. *One difference between them is that all the items belonging to a list can be of different data type* * LISTS CAN BE UPDATED * LISTS CAN BE DELETED (del list[2]) len([1, 2, 3]) -->3--> Length [2, 3] + [4, 5] -->[2, 3, 4, 5]-->Concat. ['Hi!'] * 3 -->['Hi!', 'Hi!', 'Hi'] --> Repet 3 in [1, 2, 3]-->True-->Membership for x in [1, 2, 3]: -- > print x,-->1 2 3 Iteration Functions cmp(list1, list2) len(list) max(list) list(seq) -- > convert tuple into list Methods *list.append(obj)* -- > aList = [123, 'xyz', 'zara', 'abc']; aList.append( 2009 ); *list.count(obj)* -- > aList = [123, 'xyz', 'zara', 'abc', 123]; aList.count(123) *list.extend(seq)* -- > aList = [123, 'xyz', 'zara', 'abc', 123]; bList = [2009, 'manni']; aList.extend(bList) *list.insert(index, obj)* -- > aList = [123, 'xyz', 'zara', 'abc'] aList.insert( 3, 2009) inserts object obj into list at offset index. *list.remove(obj)* -- > Removes object obj from list *list.reverse()* -- > Reverses objects of list in place

TUPLES (members can be any data type) (A tuple is a sequence of immutable Python objects) Any set of multiple objects, comma-separated, written without identifying symbols, i.e., brackets for lists, parentheses for tuples, etc., default to tuples *cmp(tuple1, tuple2)* -- >Compares elements of both tuples. *len(tuple)* -- > Gives the total length of the tuple. *tuple(seq)* -- > Converts a list into tuple.

A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses. Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while *tuples are enclosed in parentheses ( ( ) ) and cannot be updated.* Tuples can be thought of as read-only lists. tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 ) tuple[2] = 1000 # Invalid with tuple list[2] = 1000 # Valid with list The empty tuple is written as two parentheses containing nothing − tup1 = (); To write a tuple containing a single value you have to include a comma, even though there is only one value − tup1 = (50,);

*super()*

Always use super to reference the parent class. What you intend is to reference the parent class that is next-in-line, not specifically the one you see the child inheriting from.

*Data Hiding*

An object's attributes may or may not be visible outside the class definition. You need to name attributes with a double underscore prefix, and those attributes then are not be directly visible to outsiders. Python protects those members by internally changing the name to include the class name. You can access such attributes as *object._className__attrName*.

*BitStruct*

BitStruct(name, *subcons) A struct of bitwise fields :param name: the name of the struct :param \*subcons: the subcons that make up this structure

in python we do not need to declare the data type compared to C or C++

C, C++ -- > int number = 10, string name = 'davit' python -- > number = 10, name = 'davit', number = 'davit'

To create an instance/object of a class, call the class using the class name and pass in whatever arguments its *__init__* method accepts

Class contains some class variables, some data members and some methods (functions). So, the class has some attributes that are available to its objects. The attributes have to be accessed through object by using *dot .* operator. *getattr(obj, name[, default])* - to access to the attributes of object *hasattr(obj, name)* - to check if an attribute exists or not *setattr(obj, name, value)* - to set an attribute, would be created if does not exist. *delattr(obj, name)* - to delete an attribute *issubclass(sub, sup)* - the boolean function returns true if the given subclass sub is indeed a subclass of the superclass os the superclass sup. *isinstance(obj, class)* - the boolean function return true if obj is an instance of class Class is an instance of a subclass of Class

Starting an identifier with a single leading underscore indicates that the identifier is private. Starting an identifier with two leading underscore indicates that the identifier is strongly private. If the identifier also ends with two trailing underscores, the identifier is a language-defined special name.

Class name must start by uppercase character

*decorator*

Decorator is a function which takes a function as argument adds some more functionalities to passed function and return a new function without altering the source code of the passed function

MODULES

Grouping the related codes into one module. A module can define a function, classes and variables A module can also include a runnble code

How to turn the list into a comma-sepaated values. (*join*) courses = ['Art', 'Chemisty', 'CompSki', 'History'] courses_str = ' - '.join(courses) print(courses_str) Art - Chemisty - CompSki - History

How to turn the string into a list. (*split*) new_list = courses_str.split(' - ') print(new_list) ["Art", "Chemisty", "CompSki", "History"]

*Class:* - a user-defined prototype that defines a set of attributes that characterize any object of the class. *Object* - a unique instance of a data structure that's defined by the class. *Class variable* - a variable that is shared by all instances of a class. *Method* - a special kind of function that is defined in a class definition. In order to execute the method a a class, the object of that class is necessary. *Function overloading* - assignment of more that one behavior to a particular function. *Inheritance* - the transfer of the characteristics of a class to the other classes that are derived from it.

INSTANCE = OBJECT

Python does not support a character type; these are treated as strings of length one, thus also considered a sub-string.

If the else statement is used with a while loop, the else statement is executed when the condition becomes false. *while -- > else* *for -- > else*

Package in Python

If we want to import several functions from different modules then instead of importing them one by one we can make a *__init__.py* file putting all of them in this file. After the *__init.py__* package has been built, we can call the package. Package is a folder

Variable scopes

LEGB Local, Enclosing, Global, Built-in Enclosing scope deals with nested functions x = "global x" def outer(): x = "outer x" def inner(): x = "inner x" print(x) inner() print(x) outer() print(x) *1.* python checks whether there is the variable within the local scope of the called function *2.* python checks whether there is the variable within the local scope of the enclosing function *3.* python checks whether there is the variable within the global scope *4.* python checks whether there is the variable within build-in functions

*Garbage collection*

Python deleted unnecessary objects automatically to free memory space. This process is termed as garbage collection.

| Sequence("foo", | UBInt8("first_element"), | UBInt16("second_element"), | Padding(2), | UBInt8("third_element"), | )

Method resolution order: | Sequence | Struct | Construct | builtins.object | Methods inherited from Construct: | | __copy__(self) | returns a copy of this construct | | __getstate__(self) | Obtain a dictionary representing this construct's state. | | __repr__(self) | | __setstate__(self, attrs) | Set this construct's state to a given state. | | build(self, obj) | Build an object in memory. | | build_stream(self, obj, stream) | Build an object directly into a stream. | | parse(self, data) | Parse an in-memory buffer. | | Strings, buffers, memoryviews, and other complete buffers can be | parsed with this method. | | parse_stream(self, stream) | Parse a stream. | | Files, pipes, sockets, and other streaming sources of data are handled | by this method. | | sizeof(self, context=None)

*Instance Objects, __init__*

Now what can we do with instance objects? The only operations understood by instance objects are attribute references. There are two kinds of valid attribute names, *data attributes* and *methods*. *data attributes* correspond to "instance variables" in Smalltalk, and to "data members" in C++. Data attributes need not be declared; like local variables, they spring into existence when they are first assigned to. A *method* is a function that "belongs to" an object. (In Python, the term method is not unique to class instances: other object types can have methods as well. For example, list objects have methods called append, insert, remove, sort, and so on. class Complex: def __init__(self, realpart, imagpart): self.r = realpart self.i = imagpart x = Complex(3.0, -4.5) print(x.r) print(x.i)

DICTIONARY Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples. Updating Dictionary dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} dict['Age'] = 8; # update existing entry dict['School'] = "DPS School"; # Add new entry Delete Dictionary Elements dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} del dict['Name']; # remove entry with key 'Name' dict.clear(); # remove all entries in dict del dict ; # delete entire dictionary More than one entry per key not allowed. Which means no duplicate key is allowed. When duplicate keys encountered during assignment, the last assignment wins. Keys must be immutable. Which means you can use strings, numbers or tuples as dictionary keys but something like ['key'] is not allowed. *str(dict)* -- > Produces a printable string representation of a dictionary METHODS *dict.clear()* -- > Removes all elements of dictionary dict *dict.copy()* -- > Returns a shallow copy of dictionary dict *dict.fromkeys()* -- > Create a new dictionary with keys from seq and values set to value. seq = ('name', 'age', 'sex') dict = dict.fromkeys(seq) print "New Dictionary : %s" % str(dict) dict = dict.fromkeys(seq, 10) print "New Dictionary : %s" % str(dict) *dict.get(key, default=None)* -- > For key key, returns value or default if key not in dictionary *dict.has_key(key)* -- > Returns true if key in dictionary dict, false otherwise *dict.items()* --> Returns a list of dict's (key, value) tuple pairs dict = {'Name': 'Zara', 'Age': 7} print "Value : %s" % dict.items() Value : [('Age', 7), ('Name', 'Zara')] *dict.keys()* -- > Returns list of dictionary dict's keys dict = {'Name': 'Zara', 'Age': 7} print "Value : %s" % dict.keys() Value : ['Age', 'Name'] *dict.setdefault(key, default=None)* -- > The method setdefault() is similar to get(), but will set dict[key]=default if key is not already in dict. *dict.update(dict2)* -- > Adds dictionary dict2's key-values pairs to dict dict = {'Name': 'Zara', 'Age': 7} dict2 = {'Sex': 'female' } print dict.update(dict2) Value : {'Age': 7, 'Name': 'Zara', 'Sex': 'female'} *dict.values()* -- > Returns list of dictionary dict's values dict = {'Name': 'Zara', 'Age': 7} print "Value : %s" % dict.values() Value : [7, 'Zara']

Python's dictionaries consist of key-value pairs. A dictionary *key* can be almost any Python type, but are usually numbers or strings. *Values*, on the other hand, can be any arbitrary Python object. Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]) dict = {} dict['one'] = "This is one" dict[2] = "This is two" tinydict = {'name': 'john','code':6734, 'dept': 'sales'} print dict['one'] # for 'one' key print dict[2] # for 2 key print tinydict # complete dictionary print tinydict.keys() # all the keys print tinydict.values() # all the values This produce the following result − This is one This is two {'dept': 'sales', 'code': 6734, 'name': 'john'} ['dept', 'code', 'name'] ['sales', 6734, 'john']

*Set() -- {}* To create an empty set *empty_set = set()*

Set are unordered set of values with no duplicates. The main use is for checking if a value is within the set. Membership check. print("Math" in courses) True -- > works but sets are better set_courses = {"History", "Math", "Physics", "CompSki", "Math"} print(set(set_courses)) {"History", "Math", "Physics", "CompSki"} -- > no duplicate

*Overriding Methods* You can always override your parent class methods. One reason for overriding parent's methods is because you may want special or different functionality in your subclass.

Similar way, you can drive a class from multiple parent classes as follows − class A: # define your class A ..... class B: # define your class B ..... class C(A, B): # subclass of A and B .....

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.

Light Virtual Access Point Abstraction

The LVAP abstraction provides a high-level interface for wireless clients state management. A client attempting to join the network, will trigger the creation of a new LVAP. Specifically, in WiFi, an LVAP is a per-client virtual access point which simplifies network management and introduces seamless mobility support, i.e., the LVAP abstraction captures the complexities of the IEEE 802.11 protocol stack such as handling of client associations, authentication, and handovers. More specifically, every newly received probe request frame from a client at a WTP is forwarded to the controller which may trigger the generation of a probe response frame through the creation of an LVAP at the requesting WTP. The LVAP will thus become a potential candidate AP for the client to perform an association. Similarly each WTP will host as many LVAPs as the number of wireless clients that are currently under its control. Such LVAP has a BSSID that is specific to the newly associated client. Removing a LVAP from a WTP and instantiating it on another WTP effectively results in a handover.

*Classes*

The class statement creates a new class definition. The name of the class immediately follows the keyword class followed by a colon as follows *class* ClassName: ''Optional class documentation string'' *class_suite* The class has a documentation string, which can be accessed via *ClassName.__doc__*. The *class_suite* consists of all the component statements defining class members, data attributes and functions. *__init__()* method in class acts as constructor. The object of the class is initialized by this special function. But an object can be derived from a Parent class even without a constructor. But if we put __init__ the the one of the Parent class will be overridden

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.

The *read()* Method

The read() method reads a string from an open file. It is important to note that Python strings can have binary data. apart from text data. Syntax fileObject.read([count]); Here, passed parameter is the number of bytes to be read from the opened 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, maybe until the end of file. # Open a file fo = open("foo.txt", "r+") str = fo.read(10); print "Read String is : ", str # Close opend file fo.close() This produces the following result − Read String is : Python is

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. Syntax fileObject.write(string); # Open a file fo = open("foo.txt", "wb") fo.write( "Python is a great language.\nYeah its great!!\n"); # Close opend file fo.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!!

*Overloading*

This is when a function has several different definition within the same class

*enumerate*

To access the index in a list as well as the value we can use *enumerate* function courses = ['Art', 'Chemisty', 'CompSki', 'History', 'Math', 'Physics'] for index, course in enumerate(courses, start=1): print(index, course) 1 Art 2 Chemisty 3 CompSki 4 History 5 Math 6 Physics

*Static method* we shall use a static method when we are not going to use any instance/CLASS variable

What about staticmethod? It's pretty similar to classmethod but doesn't take any obligatory parameters (like a class method or instance method does). Let's look at the next use case. We have a date string that we want to validate somehow. This task is also logically bound to Date class we've used so far, but still doesn't require instantiation of it. Here is where staticmethod can be useful. Let's look at the next piece of code: @staticmethod def is_date_valid(date_as_string): day, month, year = map(int, date_ing.split('-')) return day <= 31 and month <= 12 and year <= 3999 # usage: is_date = Date.is_date_valid('11-09-2012') So, as we can see from usage of staticmethod, we don't have any access to what the class is- it's basically just a function, called syntactically like a method, but without access to the object and it's internals (fields and another methods), while classmethod does.

*reload()*

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. 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 reload hello module, do the following − reload(hello)

Class variable within a class method (function) can be accessed either through self or the class name

When we try to access an attribute from an instance then at first the instance variable are checked then the class variable that the instance have been derived from then, the class variables the instance have been inherited from

*Executing module as Script*

Within a module, the module's name (as a string) is available as the value of the global variable *__name__*. The code in the module will be executed, just as if you imported it,but with the *__name__* set to *__main__*. how to check if the called function is inside the current module ? *if __name__ == "__main__":*

class DemoClass: pass my_instance = DemoClass() print(dir(my_instance))

__eq__, __doc__, __ .. --> members of the objects

Multiple Assignment

a = b = c = 1 Here, an integer object is created with the value 1, and all three variables are assigned to the same memory location. You can also assign multiple objects to multiple variables. For example − a,b,c = 1,2,"john" Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and one string object with the value "john" is assigned to the variable c.

*remove*

courses.remove("Math") ourses = ["History", "Physics", "CompSki" ]

*is*

check the memory location if they are the same

*INSTANCE VARIABLE*

class CirrentAccount: def __init__(self, customer_name): self.name = customer_name customer_name is called an *INSTANCE VARIABLE* NOT an OBJECT VARIABLE cuz instance id is assigned to self. The variables defined under the __init__ would be accessible in the entire class (the instance of the class) only if those variable s are being defined with *self* -- > self.name, self.surname

*instancemethod(self), classmethod(cls)* and *staticmethod*

class Date(object): def __init__(self, day=0, month=0, year=0): self.day = day self.month = month self.year = year Here we have *__init__*, a typical initializer of Python class instances, which receives arguments as a typical *instancemethod*, having the first non-optional argument (self) that holds reference to a newly created instance. Let's assume that we want to create a lot of Date class instances having date information coming from outer source encoded as a string of next format ('dd-mm-yyyy'). We have to do that in different places of our source code in project. So what we must do here is: 1. Parse a string to receive day, month and year as three integer variables or a 3-item tuple consisting of that variable. 2. Instantiate Date by passing those values to initialization call. This will look like: day, month, year = map(int, string_date.split('-')) date1 = Date(day, month, year) *@classmethod* def from_string(cls, date_as_string): day, month, year = map(int, dat_string.split('-')) date1 = cls(day, month, year) return date1 date2 = Date.from_string('11-09-2012') Let's look more carefully at the above implementation, and review what advantages we have here: 1. We've implemented date string parsing in one place and it's reusable now. 2. Encapsulation works fine here (if you think that you could implement string parsing as a single function elsewhere, this solution fits OOP paradigm far better). 3. *cls* is an object that holds class itself, not an instance of the class. It's pretty cool because if we inherit our Date class, all children will have from_string defined also.

Instance variables are for data unique to each instance and class variables are for attributes and methods shared by all instances of the class:

class Dog: kind = 'canine' # class variable shared by all insts def __init__(self, name): self.name = name # inst var unique each inst >>> d = Dog('Fido') >>> e = Dog('Buddy') >>> d.kind # shared by all dogs 'canine' >>> e.kind # shared by all dogs 'canine' >>> d.name # unique to d 'Fido' >>> e.name # unique to e 'Buddy'

Like a structure in "C"

class Employee: pass john = Employee() # Create an empty employ rec. # Fill the fields of the record john.name = 'John Doe' john.dept = 'computer lab' john.salary = 1000

class MyClass(object): ... def get_my_attr(self): ... def set_my_attr(self, value): ...

class MyClass(object): ... @property def my_attr(self): ... @my_attr.setter def my_attr(self, value): ...

*self* class DemoClass: def demo_method(self): print("Hello) my_object = DemoClass() my_object.demo_method() *self* is there to tell the method which particular object it belongs to id(my_object) = id(self)

class MyClass: """A simple example class""" i = 12345 def f(self): return 'hello world' x = MyClass() The instance object is passed as the first argument of the function. In our example, the call *x.f()* is exactly equivalent to *MyClass().f()*. *The first argument of every class method, including init, is always a reference to the current instance of the class.*

*global namespace of a variable*

count = 2000 def Addcount(): global count count = count + 1 print(count) Addcount() print(count)

*insert*

courses = ["History", "Math", "Physics", "CompSki" ] courses.insert(0,"Chemisty") ["Chemisty", "History", "Math", "Physics", "CompSki" ]

*index*

courses.index("CompSki") 3

*pop*

courses.pop() removes the last value courses = ["History", "Math", "Physics" ] var = courses.pop() var = CompSki

*Python runs anything in the top level*

def main(): pass main() ============================= class Printname(): def __init__(self, number): print('hello {}'.format(number)) def launch(number): print(number) return Printname(number)

*def funct(*args, **kwargs)* --> allows us to accept an arbitrary number of positional and keyword arguments

def student(*args, **kwargs): print(args) print(kwargs) student('Math', 'Art', name='John', age=22) result ('Math', 'Art') {'name' : 'John', 'age' : 22} ========================================= courses = ['Math', 'Art'] info = {'name' : 'John', 'age' : 22} student(*courses, **info) result ('Math', 'Art') {'name' : 'John', 'age' : 22}

*contents manager*

f = open('test.txt', 'r') print(f.name) f.close() -- > we have to close at the end ========================== with open('test.txt', 'r') as f: f_contents = f.read() -- > read the entire file(mem) f_contents = f.readlne() --> read one line print( f_contents, end='') seek(0)--> to set the position back just using open with write mode will create a file with open('test2.txt', 'w') as f: f.write('test') *if we want to read write a binary data, we should specify 'rb' and 'wb'*

The file Object Attributes

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.

*formatting* yield the same result

hello = "hello" world = "world" print (hello + " " + world) print ("%s %s" % (hello, world)) print ("{} {}".format(hello, world)) print (' '.join([hello, world])) {:02} -- > two digits (padding 0 to one digits) {:.2f} -- > two digits after the decimal point {:,} -- > format(1000**2) -- > 1,000,000

if we use *append* method in a list, it will append the new list as another list within the appending list courses = ["History", "Math", "Physics", "CompSki" ] courses_2 = ["Art", "Education"] courses.append(courses_2) ['Chemisty', 'History', 'Math', 'Physics', 'CompSki', ['Art', 'Education']]

if we use *extend* method in a list, it will extend the current list with the new one courses = ["History", "Math", "Physics", "CompSki" ] courses_2 = ["Art", "Education"] courses.extend(courses_2) ['Chemisty', 'History', 'Math', 'Physics', 'CompSki',Art', 'Education']

encode -- > convert ASCII into binary decode -- > convert binary into ASCII

import base64 Str = "this is a string example" Str = base64.b64encode(Str.encode('utf-8')) print("Encoded string: ", Str) Str = base64.b64encode(Str.decode('utf-8')) print("Decoded string: ", Str)

*Dictionary comprehension*

names = ['Bruce', 'Clerk', 'Peter', 'Logan', 'Wade'] heros = ['Batman', 'Superman', 'Spiderman', 'Wolverine', 'Deadpool'] print zip(names, heros) [*zip creates tuples matching*] # I want a dict{'name' : 'hero'} for each name, hero #in zip(names, heros) my_dict = {} for name,hero in zip(names,heros): my_dict[name] = hero print my_dict ========================== my_dict = {name:hero for name, hero in zip(name, heros)} print my_dict # is the name is not equal to Peter , we just add in {} if name != 'Peter'

The triple quotes are used to span the string across multiple lines. (a b)

paragraph = """This is a paragraph. It is made up of multiple lines and sentences.""" if the arguments are within () [] {} then no / is required to span lines

Raw strings do not treat the backslash as a special character at all.

print 'C:\\nowhere' When the above code is executed, it produces the following result − C:\nowhere Now let's make use of raw string. We would put expression in r'expression' as follows − #!/usr/bin/python print *r'*C:\\nowhere' When the above code is executed, it produces the following result − C:\\nowhere

*import random* *choice(seq)* -- > a random item from a list, tuple, or string *randrange([start], stop, [step])* *random()* -- > generate a random number between [0,1] *shuffle (lst)* -- > randomizes the items *uniform(x,y)* -- > a random float between x and y

range([start], stop, [step]) for num in range(1,6,2): print num

*intersection, difference, union*

set_courses = {"History", "Math", "Physics", "CompSki", "Math"} art_courses = {"History", "Math", "Design", "Art"} *print(set_courses.intersection(art_courses))* *print(set_courses.difference(art_courses))* *print(set_courses.union(art_courses))*

Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string and working their way from -1 at the end. The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator.

str = 'Hello World!' print str # Prints complete string print str[0] # Prints first character of the string print str[2:5] # Prints characters starting from 3rd to 5th print str[2:] # Prints string starting from 3rd character print str * 2 # Prints string two times print str + "TEST" # Prints concatenated string This will produce the following result − Hello World! H llo llo World! Hello World!Hello World! Hello World!TEST

>>> add.py 10 20 import *sys* module which is in the standard library *sys.argv* returns list object containing command line argument len(sys.argv) returns number of arguments . sys.argv[0] contains the name of the script

sys.argv is a list in Python, which contains the command-line arguments passed to the script. With the len(sys.argv) function you can count the number of arguments. If you are gonna work with command line arguments, you probably want to use sys.argv. To use sys.argv, you will first have to import the sys module.

The try-finally Clause You can use a finally: block along with a try: block. The finally block is a place to put any code that must execute, whether the try-block raised an exception or not.

try: You do your operations here; ...................... Due to any exception, this may be skipped. finally: This would always be executed. ......................

try....except...else

try: You do your operations here; ...................... except ExceptionI: If there is ExceptionI, then execute this block. except ExceptionII: If there is ExceptionII, then execute this block. ...................... else: If there is no exception then execute this block. The code in the else-block executes if the code in the try: block does not raise an exception.

The except Clause with Multiple Exceptions

try: You do your operations here; ...................... except(Exception1[, Exception2[,...ExceptionN]]]): If there is any exception from the given exception list, then execute this block. ...................... else: If there is no exception then execute this block.

The except Clause with No Exceptions

try: You do your operations here; ...................... except: If there is any exception, then execute this block. ...................... else: If there is no exception then execute this block. This kind of a try-except statement catches all the exceptions that occur. Using this kind of try-except statement is not considered a good programming practice though, because it catches all exceptions but does not make the programmer identify the root cause of the problem that may occur.

zip function

zip(axis, [y1, y2, y3], names); axis = [x, y, z]; names = [Davit, Artur, Gagik] instead of iteration on each separately, you can iterate just once. for as,y,name in zip(axis, [y1, y2, y3], names) zip zip_longest (from itertools import zip_longest)

| Struct("foo", | UBInt8("first_element"), | UBInt16("second_element"), | Padding(2), | UBInt8("third_element"), | ) *:param name:* the name of the structure *:param subcons:* a sequence of subconstructs that make up this structure.

| Methods inherited from Construct: | | *__copy__(self)* | returns a copy of this construct | | *__getstate__(self)* | Obtain a dictionary representing this construct's state. | | *__repr__(self)* | | *__setstate__(self, attrs)* | Set this construct's state to a given state. | | *build(self, obj)* | Build an object in memory. | | *build_stream(self, obj, stream)* | Build an object directly into a stream. | | *parse(self, data)* | Parse an in-memory buffer. | | Strings, buffers, memoryviews, and other complete buffers can be | parsed with this method. | | *parse_stream(self, stream)* | Parse a stream. | | Files, pipes, sockets, and other streaming sources of data are handled | by this method. | | *sizeof(self, context=None)* Calculate the size of this object, optionally using a context.


Ensembles d'études connexes

mastering A and P chap 21 (I, II)

View Set

Pharmacology PrepU Chapter 9: Antibiotics

View Set

APSUSH Period 4 Exam Study Guide

View Set

Business Tech Chapter 1 Practice Quiz

View Set

Chapters 4-6 Criminal Justice Study guide

View Set