# classes.py
# Simple examples
class C:
pass
x = C()
x.a = 1
print 'x.a is', x.a
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
my_point = Point(3,4)
print 'x, y: %s, %s' % (my_point.x, my_point.y)
print
# Class attributes shared across instances
class C:
x = None
def __init__(self, value):
C.x = value
a = C('foo')
print 'C.x from a.x is', a.x
b = C('abc')
print 'C.x from a.x is', a.x
print
# Inheritance
class Para:
def __init__(self, fontsize):
self.fontsize = fontsize
class Code(Para):
pass
para = Code(12)
print "para.fontsize is", para.fontsize
# Overriding base class
class Para:
def __init__(self, text, fontsize):
self.text = text
self.fontsize = fontsize
def output(self):
s = []
s.append('' % self.fontsize)
s.append(self.text)
s.append('')
return ''.join(s)
class Code(Para):
def output(self):
s = []
s.append('')
s.append('' % self.fontsize)
s.append(self.text)
s.append('')
s.append('')
return ''.join(s)
print Para('Hi there!', 15).output()
print Code('Hi there!', 15).output()
# Accessing base class
class Code(Para):
def output(self):
base = Para.output(self)
return '' + base + ''
print Code('Hi there!', 15).output()
print
# Polymorphism without inheritance
class FakeFile:
def __init__(self, lines):
self.lines = lines
self.lineNum = 0
def readline(self):
try:
line = self.lines[self.lineNum]
self.lineNum += 1
return line
except IndexError:
return ''
configText = [
'[default]',
'a=foo',
'b=3'
]
configFile = FakeFile(configText)
import ConfigParser
config = ConfigParser.ConfigParser()
config.readfp(configFile)
for section in config.sections():
for option in config.options(section):
value = config.get(section, option)
print section, ':', option, ':', value
print
# Multiple inheritance / Mix-ins
# Most multiple inheritance in Python is mix-in
# Use to inherit specific behavior
class ThreadMixin:
def new_handler(self):
return "Threaded handler"
class ForkMixin:
def new_handler(self):
return "Forked handler"
class Server:
pass
class ThreadedServer(ThreadMixin, Server):
pass
class ForkedServer(ForkMixin, Server):
pass
myServer = ThreadedServer()
print myServer.new_handler()
print
# Full example with has-a and is-a
class Person:
def __init__(self, name, address):
self.name = name
self.address = address
# Virtual base class
class Employee:
def __init__(self, person):
if self.__class__ == Employee:
raise NotImplementedError
else:
self.person = person
def GetPay(self):
raise NotImplementedError
class SalariedEmployee(Employee):
def __init__(self, person, salary):
Employee.__init__(self, person)
self.salary = salary
def GetPay(self):
return self.salary
person = Person('John Smith', 'San Diego, CA')
try:
emp = Employee(person)
except NotImplementedError:
print "Sorry, can't create instances of Employee"
emp = SalariedEmployee(person, 100000)
print "%s's salary is %s" % (emp.person.name, emp.GetPay())