- Shuffle
Toggle OnToggle Off
- Alphabetize
Toggle OnToggle Off
- Front First
Toggle OnToggle Off
- Both Sides
Toggle OnToggle Off
Front
How to study your flashcards.
Right/Left arrow keys: Navigate between flashcards.right arrow keyleft arrow key
Up/Down arrow keys: Flip the card between the front and back.down keyup key
H key: Show hint (3rd side).h key
![]()
PLAY BUTTON
![]()
PLAY BUTTON
![]()
181 Cards in this Set
- Front
- Back
- 3rd side (hint)
|
There is some limited support for functional programming
|
But good support for procedural and OOP
|
|
|
There are some (four)
basic programming concepts in OOP: |
Abstraction
Polymorphism Encapsulation Inheritance |
|
|
Abstraction is ....
|
simplifying complex reality by modelling classes appropriate to the problem.
|
|
|
Polymorphism is ...
|
the process of using an operator, or function,
in different ways for different data input. |
|
|
Encapsulation ....
|
hides the implementation details
of a class from other objects. Python does not do this well |
|
|
Inheritance is
|
a way to form new classes using classes
that have already been defined |
|
|
Everything in Python is what?
|
an object !!
|
|
|
print type(1)
what type?? |
int
|
|
|
print (type(""))
what type? |
str
|
|
|
print type([])
what type? |
list
|
|
|
print (type({}))
what type? |
dict
|
|
|
print type(())
what type? |
tuple
|
|
|
print (type(object))
what type? |
type
!!! |
|
|
if
def func(): pass then what is print (type(func)) ie what type? |
function
|
|
|
print (type(sys))
what type? n.b. import sys |
module
|
|
|
The user defined objects are created how?
|
using the class keyword
|
|
|
From classes we what?
|
We construct instances.
The class is a blueprint that defines a nature of a future object. |
|
|
Make an empty class
|
Use pass
class First: pass |
|
|
class or Class??
|
class is the reserved keyword
|
|
|
Make an instance of First
|
fr = First ()
|
|
|
Class name convention
|
itself, class is lowercase,
but the classname is Uppercase: eg class First: don't forget the damn colon |
|
|
Inside a class, we can define
|
attributes and methods.
Technically, attributes are variables and methods are functions defined inside a class. |
|
|
An attribute is
|
a characteristic of an object.
|
|
|
A method
|
defines operations that we can perform with our objects.
|
|
|
What initializes (the attributes (of an object))
|
A special method called __init__() is used to initialize the attributes of an object.
|
|
|
Create and init class Cat
|
class Cat:
def __init__(self, name): self.name = name |
|
|
Each method in a class definition begins with ...
|
a reference to the ** instance object**.
It is by convention named self. A very strong convention. |
It seems we do this to avoid confusion with methods defined outside the class...? |
|
When is the _init_() value passed?
|
The value is passed during the class instantiation.
|
|
|
re: class Cat before...
type Cat at >>> prompt in IDLE you get what |
<class '__main__.Cat'>
|
|
|
What is __main__
|
__main__
— Top-level script environment This module represents the (otherwise anonymous) scope in which the interpreter’s main program executes... |
...commands read either from standard input, from a script file, or from an interactive prompt. (http://docs.python.org/library/__main__.html) |
|
What do we know about 'class object attributes'?
|
Class object attributes are same for all instances of a class.
|
|
|
If a Cat is a mammal named missy, species Cat
(study 'class instance attributes') |
Then,
print (Cat.species) equals print (missy.__class__.species) equals mammal |
"The attribute is defined outside any method name in the body of a class." |
|
If a Cat is a mammal named missy, species Cat
|
Then,
print (Cat.species) equals print (missy.__class__.species) equals mammal |
There are two ways, how we can access the class object attributes. Either via the name of the Cat class, or with the help of a special __class__ attribute. |
|
What are methods?
They are used to perform operations with the attributes of our objects. Methods are essential in encapsulation concept of the OOP paradigm. For example, we might have a connect() method in our AccessDatabase class. We need not to be informed, how exactly the method connect connects to the database. We only know, that it is used to connect to a database. This is essential in dividing responsibilities in programming. Especially in large applications. |
Methods are functions defined inside the body of a class.
They are used to perform operations with the attributes of our objects. |
Methods are essential in encapsulation concept of the OOP paradigm. This is essential in dividing responsibilities in programming. Especially in large applications. |
|
What does this do?
def setRadius(self,radius): self.radius = radius |
Lets you set a value for radius
with call "c.setRadius(5)" now radius = 5 |
|
|
For c who is paired with what?
(class Circle example) |
The method is called *on* an instance object.
The c object is paired with the self parameter of the class definition. The number 5 is paired with the radius parameter. |
|
|
How can we call methods?
|
In Python, we can call methods in two ways.
There are bounded and unbounded method calls. |
|
|
This is the bounded method call.
print m.getName() ie instance - method |
The Python interpreter automatically pairs the m instance with the self parameter.
|
example: see tutorial print m.getName() |
|
print (Methods.getName(m))
This is the unbounded method call. ie class - method- instance, in that order in the syntax |
The instance object is explicitly given to
the getName() method. The instance object is m. |
it means that the call to the method is not yet bound (as in bind) |
|
What are derived classes:
The newly formed classes are called derived classes,.... |
the classes that we derive from are called base classes.
|
|
|
How powerful are derived classes?
|
The derived classes (descendants) ***override or extend*** the functionality of base classes (ancestors).
|
|
|
Make a dog from class Animal
|
class Dog(Animal):
def __init__(self): Animal.__init__(self) |
but why Animal.__init__(self)?? |
|
Make a dog from class Animal
|
class Dog(Animal):
def __init__(self): Animal.__init__(self) |
but why Animal.__init__(self)?? |
|
Relate ancestor and descendant classes
|
We put the ancestor classes in round brackets
after the name of the descendant class. eg. sonOf(isParent), I think |
sonOf(isParent) |
|
Relate ancestor and descendant classes
|
We put the ancestor classes in round brackets after the name of the descendant class.
|
|
|
Descendant class is also called
|
derived class
|
|
|
If the derived class provides its own __init__() method, it must explicitly call the base class __init__() method
|
who would have suspected that!!!???
|
|
|
Python programming language uses polymorphism extensively in built-in types. Here we use the same indexing operator for three different data types.
|
index of string; of list; of tuple or objects
|
|
|
When is polymorphism most commonly used?
|
Polymorphism is most commonly used
when dealing with inheritance. |
|
|
How do you call operations
with special method names??? |
Classes in Python can implement certain operations
with special method names. These methods are not called directly, but by ***a specific language syntax.***, ie such as arithmetic operations or subscripting and slicing |
|
|
Vector operations
|
The author essentially overloads the + operator
so that two vectors can be added (but only if of the same dimension)!!! ie no error checking |
|
|
General def. of an Iterator
|
an iterator is an object
which allows a programmer to traverse through all the elements of a collection. |
|
|
it = iter(str)
str is a string .... so what are iter and it??? |
The iter() function returns an iterator on object;
'it' is an instance of iter which has a next method, which we will happily use |
|
|
What's wrong with
list it ? NB it = iter (str) |
should be list (it)
|
|
|
str = 'abc' is the same as str = "abc"?
|
Yup
|
|
|
Let str='abc' and it = iter(str),
how to access successive members of str? |
next(it)
|
|
|
List of an iter obj works fine; what of tupl on one?
|
if str='abc' and it=iter(str), then
tuple(it) ('a', 'b', 'c') |
|
|
What are advantages of iterators?
|
Iterators have several advantages:
1. / Cleaner code 2./ Iterators can work with infinite sequences 3./ Iterators save resources (without keeping the entire dataset in memory) |
|
|
str='abc'
it=iter(str) ... so tuple(it) is what? |
('a', 'b', 'c')
|
|
|
Where is the iterator in
for line in f: print line, |
line in f
|
|
|
Create our own object that will implement the iterator protocol... how?
|
This is a sequence of rapidly expanding numbers:
class seq: def __init__(self): self.x = 0 def next(self): self.x += 1 return self.x**self.x def __iter__(self): return self |
|
|
Can iterators work with gnarly infinite sequences?
|
Indeed.
|
|
|
Relate for to iter and next
for i in s: print i n += 1 if n > 10: break |
The for statement calls the iter() function
on the container object, s. The iter function returns an iterator object that defines the method next() which accesses elements in the container one at a time. |
|
|
What does this stupid notation mean?
n += 1 |
increment n by 1, or
n=n+1 |
|
|
How do we know that the __iter__ method
returns the iterator object? |
From the definition of the function-
def __iter__(self): return self |
|
|
How to activate a stopIteration?
|
In the class definition we must raise
a StopIteration exception. |
|
|
StopIteration is a(n) what
|
an exception
|
|
|
Generators vs Iterators
|
*Generators are iterators, but not all iterators are generators.
**An iterator is typically something that has a next method to get the next element from a stream. ***A generator is an iterator that is tied to a function. (see side 3 for source link) |
http://stackoverflow.com/questions/1022564/what-is-the-difference-between-an-iterator-and-a-generator |
|
How to find the class name of an object?
(i.e. given an object s, what class 'made' it? |
s.__class__.__name__
|
|
|
What is required to make a class definition create Iterator objects?
|
def __iter__(self):
return self I think!!!! |
|
|
Names of the five predefined class attributes in Python that
|
Attribute Type Read/Write Description
__dict__ dictionary R/W The class name space. __name__ string R/O The name of the class. __bases__ tuple of classes R/O The classes from which this class inherits. __doc__ string OR None R/W The class documentation string. __module__ string R/W The name of the module in which this class was defined |
|
|
How to instantiate a class in Python
|
Instantiating classes in Python is straightforward.
To instantiate a class, simply call the class as if it were a function, passing the arguments that the __init__() method requires. The return value will be the newly created object. |
|
|
What does this do?
print missy.__class__.species |
missy is an instance of class Cat. This goes into that class definition and finds the variable species, and prints the contents
|
|
|
Methods are defined where?
|
Methods are functions defined
inside the body of a class. They are used to perform operations with the attributes of our objects. |
|
|
If the derived class provides its own __init__() method,
it must do what? |
explicitly call the base class __init__() method
|
|
|
What 'operators' are being overloaded in the Book example?
|
len and del via __len__ and __del__.
also __str__, which is relevant to print |
|
|
In the vector examples which methods overload + and - ?
|
__add__ for + and __sub__ for -
|
|
|
In the seq example what does s=seq() denote?
|
s is an instance of seq, and is in effect an infinite sequence to be generated from 0,1,... until we introduce a break
|
|
|
What is a common alternative to break in iterators?
|
raise StopIteration
|
|
|
How are user-defined functions created?
|
using def keyword, don't forget the colon
|
|
|
Are we able to hide information?
|
Yes.
|
|
|
How to make an empty, deferred or undefined function
|
use 'pass'
|
|
|
How do we call a function?
|
just state its name (with parameters if any)
|
|
|
What could function definitions be confused with ?
|
class definitions
|
|
|
What does a function return if it does return a value?
|
oops?
|
|
|
In the module example for functions
what are the two special state attributes? |
__doc__ and __file__.
|
|
|
What is the underscore gotcha?
|
__ is a double underscore.
|
|
|
in def power(x, y=2): what is y=2?
|
a default value for y, readily overwritten.
|
|
|
How flexible is the function argument list in Python?
|
It can accept a variable number of arguments.
|
|
|
What on earth does this mean: def sum(*args):
|
*args = variable # of arguments
|
|
|
What are the ''' triple quotes?
|
Documentation string for the function
|
|
|
What is the ** construct in our functions?
|
This indicates a dictionary is an argument.
"The dictionary has arbitrary length. We can then normally parse the dictionary." |
|
|
What is the scope of a variable defined inside a function body?
|
Local, and only valid within the function body
|
|
|
When do we use the global keyword
|
Inside a function when we want to access a variable from the outside
|
|
|
Is introspection selfish?
|
No, it allows us to dynamically
inspect any object in Python |
|
|
What does the important (for introspection) dir () do???
|
The function returns a sorted list of attributes and methods belonging to an object.
|
|
|
In the tuple example, what is this?? ().__doc_
|
tuple() -> empty tuple
tuple(iterable) -> tuple initialized from iterable's items If the argument is a tuple, the return value is the same object. |
|
|
How do we check to see if something is a function?
|
use callable( )
|
|
|
What does id() do?
|
It may give the address of an object in memory,
esp in CPython |
|
|
isinstance() checks to see if
a thing is an instance of a |
if an object is an instance of
a class or type or tuple and returns Boolean |
|
|
Parse this:
The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for |
is a shortcut for
isinstance(x, A) or isinstance(x, B) or ... (etc.). |
|
|
If Dog is a class then what is the Boolean of issubclass (Dog, Dog)
|
True!
|
|
|
Grab the name of an object as i ranges over a list
|
print i.__name__
|
|
|
Finally, there is also a callable() function. The function checks, if an object is a callable object.
|
Or in other words, if an object is a function.
|
|
|
What is an exception
|
Errors detected during execution are called exceptions.
|
|
|
What could we do if we may expect an exception
|
Use try,
After try keyword, we put the code, where we expect an exception. |
|
|
Inputting is useful. What is the syntax?
|
raw_input("Enter first number:")
|
|
|
Relate input and raw_input
|
input=(eval(raw_input))
|
|
|
x, y = input_numbers() ....
what does this tell us about the function input_numbers |
it will input two numbers, first for x then one for y
|
|
|
I can dynamically add any attribute I want to my user-defined objects
|
except maybe some built-ins
|
|
|
What does this mean?
"%d / %d is %f" % (x, y, x/y) |
"%d for x
/ %d for y is %f" for x/y % (x, y, x/y) |
|
|
Objects
"Every object has ..... " |
an identity, a type and a value.
http://docs.python.org/reference/datamodel.html |
|
|
Errors detected during execution are called exceptions.
|
Even if they are 'errors' we deliberately cause or manufacture
|
|
|
what is a ZeroExceptionError
|
tried to divide by zero
|
|
|
except syntax
|
example
except ZeroDivisionError: but up-hierarchy will catch more error |
|
|
How to handle multiple exceptions
|
To handle more exceptions,
we can either use more except keywords or place the exception names inside a tuple. |
eg. except ValueError: pass except (IOError, OSError): pass |
|
Why would we provide a second argument for the except keyword?
|
We will get we get a reference to the exception object.,
print "Message:", e.message print "Class:", e.__class__ From the exception object, we can get the error message or the class name. |
|
|
What is the is the hierarchy of the KeyboardInterrupt exception.
|
Exception
BaseException KeyboardInterrupt |
|
|
Defining a new exception class.
|
class BFoundError(Exception):
def __init__(self, value): print "BFoundError: b character found at position %d" % value |
|
|
finally syntax
|
example:
finally: if f: f.close() |
There is a finally keyword, which is always executed. No matter if the exception is raised or not. It is often used to do some cleanup of resources in a program. |
|
Get a list of Python keywords
|
print "Python keywords: ", keyword.kwlist
|
|
|
duplicate a character in print
|
print ("*" * 24)
|
************************ |
|
print "\tZetCode" yields?
|
ZetCode
|
|
|
What does the comma do?
print num, |
continue to print on same line if possible
|
|
|
continue does what?
|
continue keyword: It is used to interrupt the current cycle, without jumping out of the whole cycle. New cycle will begin
|
|
|
Usage of if, elif and else
|
if blahblah:
elif blahblah2: else blahblah3: |
|
|
When is else executed?
|
If none of the tests is True, the else statement is executed.
|
|
|
Generalized use of for
|
The for keyword is used to iterate
over items of a collection in order that they appear in the container. |
|
|
See
print [] == [] print [] is [] Why is the first True and the second false? |
They are equal, but not the same:
each [] is a distinct (but unnamed) object. |
|
|
Syntax of not for list
|
list=['a','b','c']
if i not in list: pass |
|
|
What is short-circuit evaluation in Python?
|
Short circuit evaluation means that the second argument is only evaluated if the first argument does not suffice to determine the value of the expression:
|
|
|
Get pi
|
import math
print math.pi |
|
|
Why bother with from keyword?
|
to import a specific name/variable and use it directly without . dot referencing
|
|
|
What is the lambda keyword?
|
It creates a new anonymous function. An anonymous function is a function, which is not bound to a specific name.
|
It is also called an inline function. |
|
What does this mean?
a = lambda x: x * x |
a is a function such that a(x)=x*x
use like print a(i) |
no semicolon required |
|
location of global
|
use inside a def or function to access variables defined outside of the def or function
|
|
|
try, except, finally
|
try:
except blahError: finally: |
|
|
raise syntax
|
raise YesNoException
no colon |
|
|
exec keyword
|
like this, executes dynamically:
exec("for i in [1, 2, 3, 4, 5]: print i,") |
|
|
Two usages of in
|
1. print 4 in (1,2,5,6) False
2. print i in range(25) traverse the range |
|
|
What does this read?
c = sys.stdin.read(1) |
one character
|
|
|
What lets us stop a stdin.read
|
if c == '\n':
|
|
|
data = input('Enter expression: ')
|
The input() function prints a prompt if it is given, reads input and evaluates it.
|
|
|
name = raw_input('Enter your name: ')
|
The raw_input() prints a prompt if it is present. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.
|
|
|
std write out
|
sys.stdout.write('Honore de Balzac, Father Goriot\n')
|
|
|
Another form of print keyword:
If we want, we can use it to write some data into a regular file. |
f = open('works', 'w')
print >> f, 'Beatrix' |
|
|
Redirect file objects!
|
f = open('output', 'w')
sys.stdout = f |
|
|
sys.stdout = sys.__stdout__ ???
|
restores the stdout to system default
|
|
|
open function syntax
|
open(filename, [mode='r'], [bufsize])
mode = r,w,a,b,+ |
|
|
f.close()
|
good programming practice
|
|
|
Where am I in IDLE?
|
import os
os.getcwd() |
|
|
Open text file in path and read a line:
|
f = open('ifyouwantme', 'r')
use readline method on f like this line = f.readline() How to end??? if not line: break |
|
|
readline() vs readlines()
|
readlines grasps the whole file
|
|
|
what are the methods of pickle?
|
load() and dump()
|
|
|
Use pickle
|
open a file f to write to, then pickle.dump(object,f)
|
|
|
Zen of Python
|
import this
|
|
|
What does this do?
from module import * |
This construct will import all Python definitions
into the namespace of another module. There is one exception. Objects beginning with underscore character _ are not imported. |
|
|
locals() does what
|
The locals() function give us all the definitions available in the private module.
|
|
|
from module import fun, var
|
we import what we need to avoid namespace pollution
|
|
|
(a, b) = (b, a + b) is the same as
|
a = old b and b = old a + old b
|
|
|
Get a directory listing
|
print (glob.glob('*.*'))
|
|
|
Find exception errors here
|
http://python.about.com/od/pythonstandardlibrary/a/lib_exceptions.htm
|
|
|
What is a package?
hint __init__.py |
A package is a collection of modules which have a common purpose.
Technically a package is a directory which must have one special file called __init__.py |
|
|
What does __init__.py do?
|
__init__.py file makes constants\ a Python package
constants is just a name here |
|
|
When is the __init__.py file initialized?
|
The __init__.py file is initialized
when the package is imported. |
|
|
Create subpackages
|
We can also create subpackages. To access subpackages, we use the dot operator.
|
|
|
What does __all__ do?
|
"Therefore a special variable __all__
has been introduced. This variable controls what objects will be imported from a package." |
|
|
We cannot what a string?
|
modify.
|
|
|
Two string literals next to each other
|
are automatically concatenated.
|
|
|
int()
str() float() |
are obvious but check for the exceptions they raise
|
|
|
len(), isalpha(), isdigit() and isspace()
|
very useful inspect string
|
|
|
print title.upper()
print title.lower() print title.title() print title.swapcase() print title.capitalize() |
return a modified string
|
|
|
The ljust() method returns a left justified string, the rjust() method returns a right justified string.
|
If the string is smaller than the width that we provided, it is filled with spaces.
|
|
|
We use the % operator.
|
To do string interpolation,
|
|
|
%d formatting specifier.
|
The d character says, we are expecting an integer.
|
|
|
The formatting specifier
%f and %s. |
The formatting specifier
for a float value is %f and for a string %s. |
|
|
%.1f
|
float has 1 decimal place
|
|
|
The x character will format the number
in hexadecimal notation. |
The # character will add 0x to the hexadecimal number.
|
|
|
The %o character shows the number in octal format.
|
The %e character will show the number in scientific format.
|
|
|
2d %3d %4d
|
width specifiers
|
|
|
locals() and global() are
|
useful to study as an XREF (cross-reference listing)
|