HELP: Weird attribute behavior...

Ralph Allan Rice rarice at core.com
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]
		else:
			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 = [ ]
	try:
		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()
		cur.execute(sql)
		while 1:
			rec = cur.fetchone()
			if not rec: break
			# Confimed: rec tuple is different every iteration..., so is each
element...
			# rec is a tuple of immutable objects (int, string, etc)
			xr = Reading ('G', rec[0], rec[1], rec[2], rec[3])
			result.append(xr)
		cur.close()
		s.close()
		cur = None
		s = None
	except:
		raise
			
	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!

Thanks, 
Ralph



More information about the Python-list mailing list