My script shows one use for class methods, i.e. to map Relational tables and rows to objects in python. class methods come in handy when you want all objects in a class to share one method, in this case to retrieve rows from a table.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | import psycopg
from config import DSN
conn = psycopg.connect(DSN)
cursor = conn.cursor()
class Animal:
def __init__(self, id, name, breed):
self.id = id
self.name = name
self.breed = breed
class Animals:
def loadList(cls):
cursor.execute('select * from animal')
rows = cursor.fetchall()
return [Animal(row[0], row[1], row[2]) for row in rows]
classmethod(loadList)
animals = Animals()
print animals.loadList()
|
The above uses postgresql as the database, but any database with a python binding can be used.
The schema for the table above is simple:
create table animal ( id integer UNIQUE, name text, breed text);
There are only two rows for this test:
select * from animal; id | name | breed ----+------+------- 1 | sam | cat 2 | mon | cat (2 rows)
Uhm.. What is the point of using a class method instead of a normal instance method here?
You call the method loadList on the instance Animals() and not on the class Animals. Furthermore you don't use the cls passed to loadList.