Skip to content

Instantly share code, notes, and snippets.

@ldong
Created July 2, 2014 00:56
Show Gist options
  • Save ldong/6dcd3b63396d34f89a75 to your computer and use it in GitHub Desktop.
Save ldong/6dcd3b63396d34f89a75 to your computer and use it in GitHub Desktop.

Python Fast Track

Date: July 1, 2014

Speaker: Rick Copeland

Object oriented

Methods access and visibility

A single leading underscore _ indicates that the methods is non-public methods.

A double leading underscore __ indicates that the methods is not accessbile from outside of the class.

Inheritance

For example: Animal

class Animal(object):
    def __init__(self, name):
        self.name = name

class Cat(Animal):
    def __init__(self, name= 'Puss'):
        Animal.__init__(self, name)
    def say():
        print 'From Cat'

class Monkey(Animal):
    def __init__(self, name= 'George'):
        Animal.__init__(self, name)
    def say():
        print 'From Monkey'

See if it a istance of a class: isinstance(animal, Monkey)

Methods resulution order(MRO)

Multiple inheirtances

class MonkeyDog(Monkey, Dog):
	pass

print MonkeyDog.mro()

MRO uses BFS search

Polymorphism

Magic Methods

def __str__(self):
	return self._name
def __repr__(self):
	return self._name

Override attribute access

Getter

def __getattr__(self, name):
	print ''
	return ''

Setter

def __setattr__(self, name, value):
	print ''
	return ''

Get attributes

def __getattribute__(self, name):
	print ''
	return ''

From object dictionary

def __dict__():
	pass

Override container methods

For example,

def __getitem__(self, key):
	pass
def __setitem__(self, key, value):
	pass
def __delitem__(self, key):
	pass
def _contains__(self, key):
	pass
def _repr__(self, key):
	pass

However, there is a defaultdict in python.

Others Python's magic methods, aka special methods, aka "dunder" (double underscore) methods can be overwritten:

  1. Comparison override
  2. Emulating numeric types

Decorators

Function_factory

def log_function_call(message):
	def decorator(function):
		def wrapper(*args, **kwargs):
			print ''
			return ''
		print 'wrapper'
		return wrapper
	print 'return decorator'
	return decorator

or just simply use

@log_function_call
def myfunction(a,b):
	pass

Default decorators:

  1. @property
  2. @property.setter
  3. @staticmethod
  4. @classmethod

3 types of methods:

  1. Instance methods, must be called by instances.
  2. Static methods, can be called by class or instance
  3. Classmethod, can be called by class or instances.

Factory:

@log_function_call('log1')
def myfunc(a,b):
	print 'myfunc'

~~
x = log_function_call('log1')
myfunc= x(myfunc)

Decorators for caching:

def memoize(function)
	cache = {}
	def wrapper(*agrs, **kwargs):
		pass
	return wrapper

Decorators for automatically close file.

Python builtin decorators modules: decorator(enhenced with introspection)

Logging Logger

Logging module

  1. modeled after Log4J
  2. Loggers, Handlers, and Formatters
  3. Built-in Logging Handlers
  4. Logging Configuartion: manual, dict and file.

Root logger

import logging

logging.basicConfig()

log = logging.getLogger()

log
<logging.RootLogger at 0x1007db4d0>

i.e.

log.log(logging.CRITICAL, 'This is a CRITICAL message')
log.log(logging.FATAL, 'This is a FATAL message')

log.critical('MSG')
log.error('MSG')
log.warn('MSG')
log.info('MSG')
log.debug('MSG')

Sub-loggers

root = logging.getLogger()
mylogger=logging.getLogger('mylogger')
mylogger.setLevel(logging.INFO)
root.debug('stuff')
mylogger.debug('stuff') # won't log since the level is info
mylogger.propagate = 0
mylogger.info('has stopped logging since propagate is 0')

Handlers and formatters

handler = logging.StreamHandler()
mylogger.propagate = 0 # cancel its builtin handler
mylogger.handlers = [handler]  # register to it
handler.setLevel(logging.WRAN)
mylogger.info('stuff')

mylogger.propagate = 1 # restore its builtin handler
mylogger.info('stuff') # will see double logging infos
  1. python config
  2. file config

Use watch file handler for log rotate

Next time

Generators and Iterators

References

Fast track

Single and double underscores

Charming Python: Decorators make magic easy

Python Logger

Python functiontools

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment