HELP: Weird attribute behavior...

Ralph Allan Rice rarice at
Fri Jun 1 15:13:57 EDT 2001

I am developing a class that stores device reading information.  It
looks like this:

import string
import dbi, odbc

class Reading:
	__data  =  { }
	def __init__(self, type, id, timezone, datestamp, value):
		self.__data['id'] = id
		self.__data['timezone'] = timezone
		self.__data['datestamp'] =datestamp
		self.__data['value'] = value
		self.__data['type']= type
	def __getattr__(self, name):
		if name in self.__data.keys():
			return self.__data[name]
			raise AttributeError, name
	def __repr__(self):
		return "%s : %s" % (self.__data['datestamp'], self.__data['value'])

Now, there is a method in another class that creates instances of
Reading based on the number of records in a database...

(from Class User)

def getReadings():	
	s = None
	cur = None
	result = [ ]
		s = odbc.odbc("mydatabase/user/pwd")
		sql = """
			set rowcount 100
			select rec_id, timezone,date_time, data  from readings where user_id
= %d and rec_type = 'G' 
			order by date_time desc""" % self.__user['id']
		cur = s.cursor()
		while 1:
			rec = cur.fetchone()
			if not rec: break
			# Confimed: rec tuple is different every iteration..., so is each
			# rec is a tuple of immutable objects (int, string, etc)
			xr = Reading ('G', rec[0], rec[1], rec[2], rec[3])
		cur = None
		s = None
	return result

When I call this method, it returns a list of Reading instances. 
Examining each instance in the list:
ie.. (from command line):
>>> from mymods import User 
>>> s = User()
>>> r = s.getReadings()			<-- Returns a list of Reading instances
>>> r[0].id is r[1].id			<-- Compare object references of two instances
1					<-- How can this be?
>>> r[0].value is r[1].value		<-- Compare another attribute
1					<-- AGAIN??
When I print each instance of Reading, the values printed are the same.
In other words, the attributes in each instance of Reading is
referencing the SAME set of objects!  How is this possible?

My first thought was that the rec tuple returned from the cursor method
fetchone() is a tuple mutable objects, but after doing some type
checking, I have determined that the rec tuple's elements were immutable
built-ins (integer, strings, floats).

Any ideas or suggestions???  This is so baffling!


More information about the Python-list mailing list