O'Reilly logo

Python Programming On Win32 by Mark Hammond, Andy Robinson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Dynamic Attributes

We saw in Chapter 6 , that Python objects can hold any attributes you want, in addition to those defined for the class. Any Python object’s attributes and methods are held in a hidden, internal dictionary. And we have just learned how to fetch those!

The simplest way to construct an object from a database is to use an almost-empty class. Remember you can add attributes at runtime to a Python class as follows:

>>> class DumbDbRecord:
...     pass
... 
>>> r1 = DumbDbRecord()
>>> r1.CustomerID = 1234
>>> r1.Name = 'Pythonics Inc.'
>>>

It would be easy to examine a database cursor and add all attributes to an object such as this, creating a handy database record object with a clean syntax. However, this approach carries a weakness. You presumably will want to write objects that have attributes and methods important to the functioning of the program, and to keep them separate from data fetched from the database. We’ve therefore defined a class that can accept a dictionary of fields and values and keep them separate from its own attributes.

A helpful piece of Python magic is the ability to trap attribute access. We saw in Chapter 6 that a Python object can monitor attempts to set or get its attributes. If you ask an instance of this next class for an attribute it can’t find, it goes and checks in the dictionary it got from the database:

class Record: #holds arbitrary database data def __init__(self): self._dbdata = {} def loadFromDict(self, aDict): "accept all attributes in ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required