[Tutor] question about "hiding" a function/method in a class

Mike Hansen mhansen at cso.atmel.com
Fri Jun 3 15:17:38 CEST 2005

I haven't done much OO in Python yet. For various web apps we write, we usually 
write up a DB schema in a spreadsheet. Then we write the sql script that would 
create the tables in the database. I thought it would be neat to save the 
spreadsheet as a csv file and have python write the sql script. So I started to 
write the Python program.

#!/usr/bin/env python

SQLGEN takes a csv file of a database schema and writes the sql script that will 
create the
tables and fields in the database

Mike Hansen Jun 2005


class DBField(object):
     def __init__(self, fieldName):
         self.fieldName = fieldName
         self.type = ""
         self.size = 0
         self.notNull = False
         self.unique = False
         self.references = ""
         self.default = ""

     def printField(self):
         self.fieldStr = "    %s %s" %(self.fieldName, self.type)
         if self.size > 0:
             self.fieldStr = "%s(%s)" %(self.fieldStr, self.size)
         if self.notNull:
             self.fieldStr = "%s NOT NULL" %self.fieldStr
         if self.unique:
             self.fieldStr = "%s UNIQUE" %self.fieldStr
         if self.default:
             self.fieldStr = "%s DEFAULT %s" %(self.fieldStr, self.default)
         # if self.references
         return self.fieldStr

     def __getattr__(self, attrname):
         if attrname == "fieldStr":
             return self.printField()
             raise AttributeError, attrname

def main():

def test():
     areas = DBField("area")
     areas.type = "VARCHAR"
     areas.size = 80
     areas.notNull = True
     areas.unique = True
     print areas.fieldStr
     stuff = DBField("stuff")
     stuff.type = "INTEGER"
     stuff.notNull = True
     print stuff.fieldStr

if __name__ == "__main__":
     # main()

I was wondering if I should "hide" the printField function, so I or someone else 
won't do x.printField() in the main program but use the x.fieldStr attribute. If 
so, how would I do that, def __printField(self):? How would I call it from 
__getattr__? I know I'm not really hiding it ;just mangling it. On the other 
hand, I guess it doesn't matter. What do you think?


More information about the Tutor mailing list