class C:
   def meth(self, x):
      ...
   def meth(self, x, y, z):
      ...


class C:
   def meth(self, *args):
      if len(args) == 1:
         ...
      elif type(arg[0]) == int:
         ...


class C:
   def meth(self, x):
      x.operation( )                         # Zakładamy, że x robi coś właściwego


>>> rec = {}
>>> rec['name'] = 'mel'
>>> rec['age'] = 45
>>> rec['job'] = 'instruktor'
>>>
>>> print rec['name']
mel


>>> class rec: pass
...
>>> rec.name = 'mel'
>>> rec.age = 45
>>> rec.job = 'instruktor'
>>>
>>> print rec.age
45


>>> class rec: pass
...
>>> pers1 = rec( )
>>> pers1.name = 'mel'
>>> pers1.job = 'instruktor'
>>> pers1.age = 45
>>>
>>> pers2 = rec( )
>>> pers2.name = 'dawid'
>>> pers2.job = 'programista'
>>>
>>> pers1.name, pers2.name
('mel', 'dawid')


>>> class Person:
...    def __init__(self, name, job):
...       self.name = name
...       self.job = job
...    def info(self):
...       return (self.name, self.job)
...
>>> mark = Person('ml', 'instruktor')
>>> dave = Person('da', 'programista')
>>>
>>> mark.job, dave.info( )
('instruktor', ('da', 'programista'))


# Plik employees.py

# -*- coding: utf-8 -*-
class Employee:
   def __init__(self, name, salary=0):
      self.name = name
      self.salary = salary
   def giveRaise(self, percent):
      self.salary = self.salary + (self.salary * percent)
   def work(self):
      print self.name, "robi różne rzeczy"
   def __repr__(self):
      return "<Pracownik: name=%s, salary=%s>" % (self.name, self.salary)

class Chef(Employee):
   def __init__(self, name):
      Employee.__init__(self, name, 50000)
   def work(self):
      print self.name, "przygotowuje jedzenie"

class Server(Employee):
   def __init__(self, name):
      Employee.__init__(self, name, 40000)
   def work(self):
      print self.name, "obsługuje klienta"

class PizzaRobot(Chef):
   def __init__(self, name):
      Chef.__init__(self, name)
   def work(self):
      print self.name, "przygotowuje pizzę"

if __name__ == "__main__":
   bob = PizzaRobot('robert')                # Tworzy robota o imieniu Robert
   print bob                                 # Wykonuje odziedziczoną metodę __repr__
   bob.work( )                               # Wykonuje działanie specyficzne dla typu
   bob.giveRaise(0.20)                       # Daje robotowi 20-procentową podwyżkę
   print bob; print

   for klass in Employee, Chef, Server, PizzaRobot:
      obj = klass(klass.__name__)
      obj.work( )


C:\python\examples> python employees.py
<Employee: name=robert, salary=50000>
robert przygotowuje pizzę
<Employee: name=robert, salary=60000.0>

Employee robi różne rzeczy
Chef przygotowuje jedzenie
Server obsługuje klienta
PizzaRobot przygotowuje pizzę


# Plik pizzashop.py

# -*- coding: utf-8 -*-
from employees import PizzaRobot, Server

class Customer:
   def __init__(self, name):
      self.name = name
   def order(self, server):
      print self.name, "zamawia od", server
   def pay(self, server):
      print self.name, "płaci za zamówienie", server

class Oven:
   def bake(self):
      print "piec piecze"

class PizzaShop:
   def __init__(self):
      self.server = Server('Ernest')         # Osadzenie innych obiektów
      self.chef = PizzaRobot('Robert')       # Robot o imieniu Robert
      self.oven = Oven( )
   def order(self, name):
      customer = Customer(name)              # Aktywacja innych obiektów
      customer.order(self.server)            # Klient zamawia od kelnera
      self.chef.work( )
      self.oven.bake( )
      customer.pay(self.server)

if __name__ == "__main__":
   scene = PizzaShop( )                      # Utworzenie kompozytu
   scene.order('Amadeusz')                   # Symulacja zamówienia Amadeusza
   print '...'
   scene.order('Aleksander')                 # Symulacja zamówienia Aleksandra

   
C:\python\examples> python pizzashop.py

Amadeusz zamawia od <Pracownik: name=Ernest, salary=40000>
Robert przygotowuje pizzę
piec piecze
Amadeusz płaci za zamówienie <Pracownik: name=Ernest, salary=40000>
...
Aleksander zamawia od <Pracownik: name=Ernest, salary=40000>
Robert przygotowuje pizzę
piec piecze
Aleksander płaci za zamówienie <Pracownik: name=Ernest, salary=40000>
   
   
def processor(reader, converter, writer):
   while 1:
      data = reader.read()
      if not data: break
      data = converter(data)
      writer.write(data)


# Plik streams.py

# -*- coding: utf-8 -*-
class Processor:
   def __init__(self, reader, writer):
      self.reader = reader
      self.writer = writer
   def process(self):
      while 1:
         data = self.reader.readline( )
         if not data: break
         data = self.converter(data)
         self.writer.write(data)
   def converter(self, data):
      assert 0, 'konwerter musi być zdefiniowany'


# Plik converters.py

# -*- coding: utf-8 -*-
from streams import Processor

class Uppercase(Processor):
   def converter(self, data):
      return data.upper( )

if __name__ == '__main__':
   import sys
   Uppercase(open('spam.txt'), sys.stdout).process( )      

   
C:\lp3e> type spam.txt
mielonka
Mielonka
MIELONKA!

C:\lp3e> python converters.py
MIELONKA
MIELONKA
MIELONKA!   
   

C:\lp3e> python
>>> import converters
>>> prog = converters.Uppercase(open('spam.txt'), open('spamup.txt', 'w'))
>>> prog.process( )

C:\lp3e> type spamup.txt
MIELONKA
MIELONKA
MIELONKA!
   

C:\lp3e> python
>>> from converters import Uppercase
>>>
>>> class HTMLize:
...    def write(self, line):
...       print '<PRE>%s</PRE>' % line[:-1]
...
>>> Uppercase(open('spam.txt'), HTMLize( )).process( )
<PRE>MIELONKA</PRE>
<PRE>MIELONKA</PRE>
<PRE>MIELONKA!</PRE>


import pickle
object = someClass( )
file = open(filename, 'wb')                  # Utworzenie pliku zewnętrznego
pickle.dump(object, file)                    # Zapisanie obiektu w pliku

import pickle
file = open(filename, 'rb')
object = pickle.load(file)                   # Pobranie go z powrotem później


import shelve
object = someClass( )
dbase = shelve.open('filename')
dbase['key'] = object                        # Zapisanie pod kluczem

import shelve
dbase = shelve.open('filename')
object = dbase['key']                        # Pobranie z powrotem później


# Plik trace.py

# -*- coding: utf-8 -*-
class wrapper:
   def __init__(self, object):
      self.wrapped = object                  # Zapisanie obiektu
   def __getattr__(self, attrname):
      print 'Śledzenie:', attrname           # Pobranie śledzenia
      return getattr(self.wrapped, attrname) # Delegacja pobierania


>>> from trace import wrapper
>>> x = wrapper([1,2,3])                     # Opakowanie listy
>>> x.append(4)                              # Delegacja do metody listy
Śledzenie: append
>>> x.wrapped                                # Wyświetlenie mojej składowej
[1, 2, 3, 4]
>>> x = wrapper({"a": 1, "b": 2})            # Opakowanie słownika
>>> x.keys( ) 1                              # Delegacja do metody słownika
Śledzenie: keys
['a', 'b']


>>> class Spam:
...    def __init__(self):                   # Nie ma __repr__
...       self.data1 = "jedzenie"
...
>>> X = Spam( )
>>> print X                                  # Wygląd domyślny: klasa, adres
<__main__.Spam instance at 0x00864818>


# Plik mytools.py

# -*- coding: utf-8 -*-

###########################################
# Funkcję Lister można wmieszać w każdą
# klasę w celu udostępnienia sformatowanego
# wyświetlania instancji za pomocą
# dziedziczenia poniższej metody __repr__.
# self jest instancją najniższej klasy.
###########################################

class Lister:
   def __repr__(self):
      return ("<Instancja klasy %s, adres %s:\n%s>" %
              (self.__class__.__name__,      # Nazwa mojej klasy
               id(self),                     # Mój adres
               self.attrnames( )) )          # Lista nazwa=wartość
   def attrnames(self):
      result = ''
      for attr in self.__dict__.keys( ):     # Słownik przestrzeni nazw instancji
         if attr[:2] == '__':
            result = result + "\tzmienna %s=<built-in>\n" % attr
         else:
            result = result + "\tzmienna %s=%s\n" % (attr, self.__dict__ [attr])
      return result


>>> from mytools import Lister
>>> class Spam(Lister):
...    def __init__(self):
...       self.data1 = 'jedzenie'
...
>>> x = Spam( )
>>> x
<Instancja klasy Spam, adres 8821568:
      zmienna data1=jedzenie
>


# Plik testmixin.py

# -*- coding: utf-8 -*-
from mytools import Lister                   # Pobranie klasy z narzędziami

class Super:
   def __init__(self):                       # Metoda __init__ klasy nadrzędnej
      self.data1 = "mielonka"

class Sub(Super, Lister):                    # Wmieszanie metody __repr__
   def __init__(self):                       # Klasa Lister ma dostęp do self
      Super.__init__(self)
      self.data2 = "jajka"                   # Więcej atrybutów instancji
      self.data3 = 42

if __name__ == "__main__":
   X = Sub( )
   print X                                   # Wmieszana metoda repr


C:\lp3e> python testmixin.py
<Instancja klasy Sub, adres 7833392:
      zmienna data3=42
      zmienna data2=jajka
      zmienna data1=mielonka
>


>>> from mytools import Lister
>>> class x(Lister):
...   pass
...
>>> t = x( )
>>> t.a = 1; t.b = 2; t.c = 3
>>> t
<Instancja klasy x, adres 7797696:
      zmienna b=2
      zmienna a=1
      zmienna c=3
>


def factory(aClass, *args):                  # Krotka argumentów o zmiennej liczbie
   return apply(aClass, args)                # Wywołanie aClass lub aClass(*args)

class Spam:
   def doit(self, message):
      print message

class Person:
   def __init__(self, name, job):
      self.name = name
      self.job = job
  
object1 = factory(Spam)                      # Utworzenie obiektu Spam
object2 = factory(Person, "Guido", "guru")   # Utworzenie obiektu Person


def factory(aClass, *args, **kwargs):        # + słownik argumentów ze słowami kluczowymi
   return apply(aClass, args, kwargs)        # Wywołanie aClass

   
classname = ...odczytane z pliku konfiguracyjnego...
classarg = ...odczytane z pliku konfiguracyjnego...

import streamtypes                           # Kod można dostosować do własnych potrzeb
aclass = getattr(streamtypes, classname)     # Pobrane z modułu
reader = factory(aclass, classarg)           # Lub aclass(classarg)
processor(reader, ...)   
   
   
class Spam:
   def doit(self, message):
      print message


object1 = Spam( )
object1.doit('Witaj, świecie!')


object1 = Spam( )
x = object1.doit                             # Obiekt metody z wiązaniem: instancja + funkcja
x('Witaj, świecie!')                         # Ten sam efekt co object1.doit('...')


object1 = Spam( )
t = Spam.doit                                # Obiekt metody bez wiązania
t(object1, 'siema')                          # Przekazanie instancji


class Eggs:
   def m1(self, n):
      print n
   def m2(self):
      x = self.m1                            # Inny obiekt metody z wiązaniem
      x(42)                                  # Wygląda jak prosta funkcja

Eggs( ).m2( )                                # Wyświetla 42


# Plik docstr.py

"Jestem: docstr.__doc__"

class spam:
   "Jestem: spam.__doc__ lub docstr.spam.__doc__"
   def method(self, arg):
      "Jestem: spam.method.__doc__ lub self.method.__doc__"
      pass

def func(args):
   "Jestem: docstr.func.__doc__"
   pass


>>> import docstr
>>> docstr.__doc__
'Jestem: docstr.__doc__'

>>> docstr.spam.__doc__
'Jestem: spam.__doc__ lub docstr.spam.__doc__'

>>> docstr.spam.method.__doc__
'Jestem: spam.method.__doc__ lub self.method.__doc__'

>>> docstr.func.__doc__
'Jestem: docstr.func.__doc__'


# Ramka "Znaczenie metod z wiązaniem oraz wywołań zwrotnych"

def handler( ):
   ...wykorzystanie zmiennych globalnych dla stanu...

...
widget = Button(text='mielonka', command=handler)


class MyWidget:
   def handler(self):
      ...użycie self.attr dla stanu...
   def makewidgets(self):
      b = Button(text='mielonka', command=self.handler)