List comprehension ● topStudents = [ student for student in students if student.average >= 85 ] ● coordinates = [ (x + 5, y - 2) for x in range(1, 11) for y in range(1, 6) ] coordinates = [ ] for x in range(1, 11): for y in range(1, 6): coordinates.append( (x + 5, y – 2) )
Parameters VS Argument ● Parameter = variable in a function signature. It's a placeholder for the actual value ● Argument = actual value passed when invoking the function
Function parameters ● Standard parameters: f(x, y) ● Default values: f(x, y, z = 90) ● Arbitrary sequence: f(*args) ● Keyword params: f(**kwargs) ● They can all be introduced, in this order: f(x, y, z = 90, *args, **kwargs)
Function arguments ● Given a function f(x, y)... ● ...pass by position: f(9, 10) ● ...pass by name: f(y = 10, x = 9) ● ...unpack a list of arguments: – myParamsSequence = [9, 10] – f(*myParamsSequence) ● ...pass a map of arguments: – myParamsMap = { “x”: 9, “y”: 10” } – f(**myParamsMap)
Creating methods ● class Panda(object): def sayHello(self): print(“Hello! ^__^!”) ● self is the first parameter of instance methods, and it's passed as an implicit argument! It refers to the current instance, just like this in Java/C#.
No access control in Python If a member of an object should not be used by other objects, just prepend “_” to its name. For example: ● self._privateField = 0 ● def _privateMethod(self): pass
Multiple inheritance ● Python does not define explicit interfaces... ● ...but it supports multiple inheritance! ● class Panda(Bear, VeryCuteAnimal): pass
Static methods ● class Panda(object): @staticmethod def myStaticMethod(x, y): return x+y ● Static methods can be called via the class or via any instance
Module caching and reloading ● Importing a module executes it only the first time ● The module cache is sys.modules ● reload() reloads a module ● .pyc files to optimize loading in future sessions