473,386 Members | 1,799 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Creating object attributes

Hello-

I have created a class, FixedLengthRecord.py, that allows me to manipulate
fixed length records in the routines I write. I recently converted it to
read record layouts from an SQL server (it used to read config files) and I
am thinking of making another change to make my code cleaner [WARNING: I am
going to be violating "pure" OO theology...if that offends you, please exit
now].

The heart of the class is a dictionary named "fields" that stores the
current value, length, data type, and default value for the field. Each key
of the dictionary corresponds to a "logical name" read in from the database.
I then have "Get()" and "Set()" methods to -- as you might have guessed --
get and set the values. Other methods are Clear(), Spreadsheet(),
Serialize(), Unserialize(), etc. So, in my application code I might have
something like the following:

myRec = FixedLengthRecord( id='gsl0001', version='1.0', description='This is
my record!')

myRec.Set('first_name', 'Greg') # only field names in the record
layout may be set this way
myRec.Set('last_name', 'Lindstrom')

giver = myRec.Get('first_name')

OK...you get the idea. What I would like to do, or at least consider, is
adding an attribute for each data field value instead of adding it to the
dictionary so I could access my data as follows:

giver = myRec.first_name

I still would use the Set() methods because they insure the fields are less
than or equal to the maximum length allowed. This violates the OO paradigm
of accessor methods, but it cleans up my application code and, since I live
on reality street and not academia, I am interested in how to do it.

So, to simplify the project a tad, suppose I had a tuple of fields.

myFields = ('first_name', 'last_name')

How could I incorporate them into an class "on the fly" to produce the
equivalent of

self.first_name = 'None
self.last_name = None

Are there other ways to handle fixed length records?

Thanks!
--greg

Greg Lindstrom (501) 975-4859
NovaSys Health gr************@novasyshealth.com

"We are the music makers, and we are the dreamers of dreams" W.W.
Jul 18 '05 #1
2 1554
I think we have all done something like what you have done.

I have the class create the attributes dynamically.
Something like (not tested). I'm leaving the fixed record
parsing to you.

class FixedLengthRecord:
def __init__(self, fields):
self.fields=fields
for field in fields:
self.append(field
)
return

def __getitem__(self, key):
try: return self.__dict__[key]
except:
print "Field name '%s' not found in current record" % key
return None

def __setitem__(self, key, value):
if self.__dict__.has_key(key): self.__dict__[key]=value
else:
print "Field name '%s' not found in current record" % key
return

def __call__(self, key):
try: return self.__dict__[key]
except:
print "Field name '%s' not found in current record" % key
return None

def append(self, field, value=None):
if not self.__dict__.has_key(field): self.__dict__[field]=value
else:
print "Field name '%s' already found in current record" % key
return

Then you can do:

myFields = ('first_name', 'last_name')
record=FixedLengthRecord(myFields)
record.append('address')

then these statements work

record.first_name="Greg"
record.last_name="Lindstrom"
record.address="123 Morning Glory Lane"

and

print record('first_name') outputs in "Greg"

Eliminates need for .set and .get methods and grows fieldnames
dynamically.

I hope this is what you were looking for.

Larry Bates
Syscon, Inc.

"Greg Lindstrom" <gr************@novasyshealth.com> wrote in message
news:ma*************************************@pytho n.org...
Hello-

I have created a class, FixedLengthRecord.py, that allows me to manipulate
fixed length records in the routines I write. I recently converted it to
read record layouts from an SQL server (it used to read config files) and I am thinking of making another change to make my code cleaner [WARNING: I am going to be violating "pure" OO theology...if that offends you, please exit now].

The heart of the class is a dictionary named "fields" that stores the
current value, length, data type, and default value for the field. Each key of the dictionary corresponds to a "logical name" read in from the database. I then have "Get()" and "Set()" methods to -- as you might have guessed --
get and set the values. Other methods are Clear(), Spreadsheet(),
Serialize(), Unserialize(), etc. So, in my application code I might have
something like the following:

myRec = FixedLengthRecord( id='gsl0001', version='1.0', description='This is my record!')

myRec.Set('first_name', 'Greg') # only field names in the record
layout may be set this way
myRec.Set('last_name', 'Lindstrom')

giver = myRec.Get('first_name')

OK...you get the idea. What I would like to do, or at least consider, is
adding an attribute for each data field value instead of adding it to the
dictionary so I could access my data as follows:

giver = myRec.first_name

I still would use the Set() methods because they insure the fields are less than or equal to the maximum length allowed. This violates the OO paradigm of accessor methods, but it cleans up my application code and, since I live on reality street and not academia, I am interested in how to do it.

So, to simplify the project a tad, suppose I had a tuple of fields.

myFields = ('first_name', 'last_name')

How could I incorporate them into an class "on the fly" to produce the
equivalent of

self.first_name = 'None
self.last_name = None

Are there other ways to handle fixed length records?

Thanks!
--greg

Greg Lindstrom (501) 975-4859
NovaSys Health gr************@novasyshealth.com

"We are the music makers, and we are the dreamers of dreams" W.W.

Jul 18 '05 #2
Greg Lindstrom wrote:
giver = myRec.Get('first_name')

OK...you get the idea. What I would like to do, or at least consider, is
adding an attribute for each data field value instead of adding it to the
dictionary so I could access my data as follows:

giver = myRec.first_name

I still would use the Set() methods because they insure the fields are
less
than or equal to the maximum length allowed. This violates the OO
paradigm of accessor methods, but it cleans up my application code and,
since I live on reality street and not academia, I am interested in how to
I think from an OO standpoint there is no difference between attributes that
trigger accessor methods and explicit accessor methods. So no, you are not
violating what you call the "theology" and I regard as a useful means to
reduce code interdependence.
So, to simplify the project a tad, suppose I had a tuple of fields.

myFields = ('first_name', 'last_name')

How could I incorporate them into an class "on the fly" to produce the
equivalent of

self.first_name = 'None
self.last_name = None


Here is a simple approach to dynamic generation of properties. It should be
easy to expand, e. g. choose accessors based on the field type.

class Base(object):
def get(self, name):
print "get %s" % name
def set(self, name, value):
print "set %s to %s" % (name, value)

def makeAccessors(cls, name):
def get(self):
return cls.get(self, name)
def set(self, value):
return cls.set(self, name, value)
return get, set

def makeClass(fieldDefs, Base=Base, classname=None):
class Record(Base):
pass
if classname:
Record.__name__ = classname
for fd in fieldDefs:
setattr(Record, fd, property(*makeAccessors(Base, fd)))
return Record

if __name__ == "__main__":
Person = makeClass(["firstname", "surname"])
Customer = makeClass(["cust_id"], Person)
Address = makeClass(["street", "city"], Base, "Address")

c = Customer()
c.firstname = "John"
c.surname = "Neumeyer"
c.surname
c.cust_id

a = Address()
a.street = "Cannery Row"

You might also have a look at SQLObject before you invest more work in your
code.

Peter

Jul 18 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: mcmg | last post by:
Hi, I have an asp app that works fine on a windows xp machine but does not work on a windows 2000 server. I have the following code in my global.asa: <OBJECT RUNAT=Server SCOPE=SESSION...
0
by: Robert Bruce | last post by:
Hello, I'm trying to round-trip some XML out of Adobe InDesign, through my application and then back into InDesign. Tables in InDesign are created using a specific namespace like this: ...
1
by: Irfan | last post by:
Hi all I am new to DotNet and C# Is there any way to get a type of object from a string. Lets suppose i have a string variable containing a type "MyNameSpace.MyComponent" where MyComponent.dll...
2
by: Fabian | last post by:
Hi, I would like to iterate attributes of an object like foreach(attribute a in o.attributes) { ... } any way i can do that?
1
by: Massimiliano Alberti | last post by:
Now... I've began using Attributed programming (with VC++ 7.1) and, when it works, it's very useful... (but when you have to debug it, it's hell)... Now... How can I create new attributes? ...
10
by: psbasha | last post by:
HI, Is it possible to access the Methods of a class without creating object? Thanks PSB
5
by: TheSeeker | last post by:
Hi, I have run into something I would like to do, but am not sure how to code it up. I would like to perform 'set-like' operations (union, intersection, etc) on a set of objects, but have the...
1
by: Paul Childs | last post by:
Hi folks, I'll start off with the code I wrote... (ActivePython 2.4 on Windows XP SP2) ------------------------------- class FlightCondition(object): lsf = vto =
5
by: laredotornado | last post by:
Hi, I have this alert statement alert(myObj); which when executed, alerts "", or something similar. Is there a way I can see a list of attributes and values instead or do I have to write a...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.