473,240 Members | 1,625 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,240 software developers and data experts.

Dynamically create a class (or class instance) and its attributes?

Hello,

I am a Python newbie (by experience, not chronologically :) ), so if any of
this doesn't make sense my apologies in advance.

I am reading the chapter in The Python Cookbook on databases and the MySQLdb
module. In it they show an example of a recipe that lets you access fields
in a MySQL row by name rather than by column number. For example, given a
MySQL row object from a fetchone() call:

employee_name = sqlrow[field_dict['empname']]

To make the syntax easier and clearer, I would like to create a Python class
instance that would allow me to access the fields in the MySQL row as
attributes of a class created dynamically from the row structure. For
example:

employee_name = ez_sqlrow.empname

What would be the best way to create such a class or class instance? Any
code examples you have would be welcome.

Thanks
--
Robert
Jul 18 '05 #1
3 2545

This may work.

<pre>

class Dyn:
'''Dynamic class.
'''
def __init__(self, **kwds):
self.set(**kwds)

def set(self, **kwds):
for a, v in kwds.iteritems():
setattr(self, a, v)
# all attr defined at creation
# time with an initial value
c = Dyn(a1=1, a2=2, a3=3)

# more attr can be added
c.set(a4=4, a5=5)

# attr can be changed
c.a1=10
c.set(a1=20)

</pre>

/Jean Brouwers


In article <nb*****************@bignews5.bellsouth.net>, Robert Oschler
<no_replies@fake_email_address.invalid> wrote:
Hello,

I am a Python newbie (by experience, not chronologically :) ), so if any of
this doesn't make sense my apologies in advance.

I am reading the chapter in The Python Cookbook on databases and the MySQLdb
module. In it they show an example of a recipe that lets you access fields
in a MySQL row by name rather than by column number. For example, given a
MySQL row object from a fetchone() call:

employee_name = sqlrow[field_dict['empname']]

To make the syntax easier and clearer, I would like to create a Python class
instance that would allow me to access the fields in the MySQL row as
attributes of a class created dynamically from the row structure. For
example:

employee_name = ez_sqlrow.empname

What would be the best way to create such a class or class instance? Any
code examples you have would be welcome.

Thanks

Jul 18 '05 #2
Robert Oschler wrote:
To make the syntax easier and clearer, I would like to create a Python
class instance that would allow me to access the fields in the MySQL row
as attributes of a class created dynamically from the row structure. For
example:

employee_name = ez_sqlrow.empname


Here is one way:

import itertools

class Record:
def __init__(self, row):
assert len(row) == len(self.names)
self._row = row
def __getitem__(self, index):
return self._row[index]
def __setitem__(self, index, value):
self._row[index] = value
def __iter__(self):
return itertools.izip(self.names, self._row)
def __repr__(self):
return "%s(%s)" % (self.__class__.__name__,
", ".join(["%s=%r" % nv for nv in self]))

def makeProperty(index):
def get(self):
return self[index]
def set(self, value):
self[index] = value
return property(get, set)

def makeClass(classname, fieldnames, Base=Record):
class Record(Base):
names = fieldnames
Record.__name__ = classname

for index, name in enumerate(fieldnames):
setattr(Record, name, makeProperty(index))
return Record

if __name__ == "__main__":
Person = makeClass("Person", ["firstname", "lastname", "email"])
r = Person(["Robert", "Oschler", "not provided"])
print r.firstname
r.email = "ro***@no.spam"
print r.email
print "%s %s" % tuple(r[:2])
print r

which is actually a variant of something I posted a few days ago. Or you go
with SQLObject.(Am I repeating myself? Am I repeating myself :-)

Peter
Jul 18 '05 #3
On Tue, 27 Jul 2004, Robert Oschler wrote:
For example, given a MySQL row object from a fetchone() call:

employee_name = sqlrow[field_dict['empname']]

To make the syntax easier and clearer, I would like to create a Python class
instance that would allow me to access the fields in the MySQL row as
attributes of a class created dynamically from the row structure. For
example:

employee_name = ez_sqlrow.empname

What would be the best way to create such a class or class instance? Any
code examples you have would be welcome.


The other respondents have recommended using setattr(), but here's a way
that will work completely dynamically:

class ez_sql(object):

def __init__(self,sqlrow):
self._sqlrow = sqlrow

def __getattr__(self,a):
try:
return self._sqlrow[fielddict[a]]
except (IndexError,KeyError),e:
raise AttributeError,e

def __setattr__(self,a,v):
try:
self._sqlrow[fielddict[a]] = v
except KeyError:
self.__dict__[a] = v

This is a bit slower than using setattr(), but might save a good deal of
memory (especially if you keep the SQL rows around in another form).

Jul 18 '05 #4

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

Similar topics

2
by: obsidian8 | last post by:
Hi All, I have looked around for an answer to this question, but haven't found one as of yet. I'm trying to use javascript to dynamically create raido buttons. I am able to create them easily...
2
by: Marcin Grzębski | last post by:
Hi All, How to create *component* class which do now show its instance in a component bar? I want to create other class, this *component* instance collection and i know how to show that...
2
by: Sean | last post by:
Hello all, I may just not be searching for the right thing, but I've been looking for a way to dynamically create controls (and name them) in my code so that I can create only the controls I...
1
by: Chris Dunaway | last post by:
I have a legacy application that I need to build a Windows Forms application to interface with it. The legacy application keeps its configuration information in INI style files. I wish to use a...
7
by: pmclinn | last post by:
I was wondering if it is possible to dynamically create a structure. Something like this: public sub main sql = "Select Col1, Col2 from Table a" dim al as new arraylist al =...
9
by: sashang | last post by:
Hi I'd like to use metaclasses to dynamically generate a class based on a parameter to the objects init function. For example: class MetaThing(type): def __init__(cls, name, bases, dict,...
2
by: Lou | last post by:
I want to dynamically create an unknown amount of buttons into a panel. I want each button to respond to the same click event. In VB6 I would just create an array of buttons. I do know how to...
0
by: mkadasi | last post by:
I want to dynamically create instance of class stored in other application. I am writing the following code for this purpose: Here in the AssemblyFunc() I am loading the assembly of TariffClass...
1
by: Tumelo | last post by:
Write a complete C++ Object Oriented Program:Create a class named CleverBookMark that consists of the following attributes. 3.1.1 The CleverBookMark class consists of the following: ...
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 3 Jan 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). For other local times, please check World Time Buddy In...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...

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.