我在这里有我的课程模板:
import sqlite3
class Patron(object):
#Let's set some basic attributes
attributes = { "patron_id" : None,
"name" : None,
"address" : None,
"phone" : None,
"email" : None,
"fee_balance" : None,
"fees_per_day" : None,
"books_checked_out" : [],
"books_overdue" : []}
def __init__(self):
#Create a empty instance
pass
def new(self, patron_id, name, address, phone, email):
#Create an instance with new values
self.attributes["patron_id"] = patron_id
self.attributes["name"] = name
self.attributes["address"] = address
self.attributes["phone"] = phone
self.attributes["email"] = email
def retrieve(self, patron_id):
#Connect to database and prepare patron id
self.attributes["patron_id"] = patron_id
patron_database = sqlite3.connect('patrons.db')
cursor = patron_database.cursor()
t = (str(patron_id),)
#Get data from database
cursor.execute("SELECT * FROM patrons WHERE id =?", t)
data = cursor.fetchone()
#Now close your database connection
patron_database.close()
#Parse tuple into attributes
self.attributes["name"] = data[1]
self.attributes["address"] = data[2]
self.attributes["phone"] = data[3]
self.attributes["email"] = data[4]
self.attributes["fee_balance"] = data[5]
self.attributes["fees_per_day"] = data[6]
self.attributes["books_checked_out"] = data[7]
self.attributes["books_overdue"] = data[8]
def save(self):
#Connect to the database
patron_database = sqlite3.connect('patrons.db')
cursor = patron_database.cursor()
#Compile the data into a list
attributes = []
for value in self.attributes.itervalues():
attributes.append(value)
#Insert the values and save them
cursor.execute("INSERT INTO patrons VALUES(?,?,?,?,?,?,?,?,?)", attributes)
patron_database.commit()
#Close the connection
patron_database.close()
然后我在这里有我的测试代码:
'''
Created on Feb 2, 2013
@author: Zach
'''
from Patron import Patron
zach = Patron()
braden = Patron()
zach.retrieve(1187277)
print zach.attributes
print braden.attributes
我的控制台说“zach”和“braden”实例都具有完全相同的属性,即使我没有为“braden”实例设置任何内容。如果我为“braden”实例分配了一些东西,那么它们都共享该实例的属性。
我认为这是与可变默认参数行为有关的问题,但我无法弄清楚我的问题。