473,661 Members | 2,449 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Creating object attributes

Hello-

I have created a class, FixedLengthReco rd.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 = FixedLengthReco rd( id='gsl0001', version='1.0', description='Th is is
my record!')

myRec.Set('firs t_name', 'Greg') # only field names in the record
layout may be set this way
myRec.Set('last _name', 'Lindstrom')

giver = myRec.Get('firs t_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_nam e

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.c om

"We are the music makers, and we are the dreamers of dreams" W.W.
Jul 18 '05 #1
2 1565
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 FixedLengthReco rd:
def __init__(self, fields):
self.fields=fie lds
for field in fields:
self.append(fie ld
)
return

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

def __setitem__(sel f, key, value):
if self.__dict__.h as_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__.h as_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=FixedLen gthRecord(myFie lds)
record.append(' address')

then these statements work

record.first_na me="Greg"
record.last_nam e="Lindstrom"
record.address= "123 Morning Glory Lane"

and

print record('first_n ame') 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******** *************** **************@ python.org...
Hello-

I have created a class, FixedLengthReco rd.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 = FixedLengthReco rd( id='gsl0001', version='1.0', description='Th is is my record!')

myRec.Set('firs t_name', 'Greg') # only field names in the record
layout may be set this way
myRec.Set('last _name', 'Lindstrom')

giver = myRec.Get('firs t_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_nam e

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.c om

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

Jul 18 '05 #2
Greg Lindstrom wrote:
giver = myRec.Get('firs t_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_nam e

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(c ls, name):
def get(self):
return cls.get(self, name)
def set(self, value):
return cls.set(self, name, value)
return get, set

def makeClass(field Defs, Base=Base, classname=None) :
class Record(Base):
pass
if classname:
Record.__name__ = classname
for fd in fieldDefs:
setattr(Record, fd, property(*makeA ccessors(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
3990
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 ID=MyID
0
1225
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: <Table TABLE_TYPE="table05" xmlns:aid="http://ns.adobe.com/AdobeInDesign/4.0/" aid:table="table" aid:trows="7" aid:tcols="2">
1
227
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 is already been referenced in the client project. Now i want to create any object from that string. I think this require getting a type from that string and then creating object from that type. If this or any alternative is possible, pls let me...
2
4530
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
993
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? Thanks Max
10
3462
by: psbasha | last post by:
HI, Is it possible to access the Methods of a class without creating object? Thanks PSB
5
1432
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 set operations based on an attribute of the object, rather than the whole object. For instance, say I have (pseudo-code): LoTuples1 =
1
1072
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
3988
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 custom method for my object?
0
8432
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
1
8545
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8633
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7364
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5653
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4179
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4346
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2762
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1743
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.