OOP in Python Flashcards
distinguish between local and instance variables
self.x
“special features” of Python functions
functions are regular objects; passed as arguments, returned from function, modified inside functions etc.
private variable
doesn’t exist
constructor
class MyClass: def \_\_init\_\_(self, i, j): self.i = i; self.j = j; def write(self): print "i = %d" % (i)
declaring and calling instance methods
all instance methods take self as first argument in the declaration, but no in the call
obj. someMethod()
class. someMethod(obj)
equal for an instance obj of class class
class variables
class variables are common to the class;
>>>class Point(object): counter = 0 def \_\_init\_\_(self): Point.counter +=1 >>> p0 = Point() >>> p1 = Point() >>> Point.counter 2 >>> p0.counter 2
get dictionary with all class attributes
Class.__dict__
instance.__class__.__dict__
name of class
instance.__class__.__name__
list names of all methods and attributes
dir(instance)
python functions are also …
objects, and can therefore be arguments to functions
function as argument to function
def apply(func, x, y): return func(x, y)
nested function definitions
def f(x): def cube(x): return x*x*x return cube(x)
return function from function
def outer(): def inner(): .... return inner
decorate a function
@checkrange def g(x): return x**3-2
# or g = checkrange(g)