473,609 Members | 1,818 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Class initialization from a dictionary, how best?

#
# My problem is that I want to create a
# class, but the variables aren't known
# all at once. So, I use a dictionary to
# store the values in temporarily.
# Then when I have a complete set, I want to
# init a class from that dictionary.
# However, I don't want to specify the
# dictionary gets by hand
# since it is error prone.
# Thanks for any ideas, Brian
# So I have a class defined that accepts a number of variables
# and they must be all present at object creation time.
class Test:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def __str__(self):
return '%s, %s, %d' % (self.a, self.b, self.c)

# For example:
t1 = Test('asd', 'sdf', 9)
print t1

# However, due to parsing XML, I am
# creating the values incrementally
# and I want to store them in a dictionary
# and then map them easily to a class

dictionary = {}

# a mapping from source to destination
mapping = {
'a': str,
'b': str,
'c': int,
}

# a sample source of values
test_source = {
'a': 'test',
'b': 'asdf',
'c': 45
}

# now we go through and extract the values
# from our source and build the dictionary

for attr_name, function in mapping.items() :
dictionary[attr_name] = function(test_s ource.get(attr_ name))

print dictionary

# Here is the problem I want to avoid:
# Having to list the variable names
# as strings in multiple places. It is enought to
# have them in the 'mapping'
# dictionary above

t2 = Test(dictionary .get('a'), dictionary.get( 'b'),
dictionary.get( 'c'))
print t2

Jul 18 '05 #1
4 2511
br********@gmai l.com wrote:
t2 = Test(dictionary .get('a'), dictionary.get( 'b'),
dictionary.get( 'c'))
print t2


Try this:

t2 = Test(**dictiona ry)

This performs keyword argument expansion on the dictionary, matching the
dictionary entries with the named arguments to the Test.__init__ function.

Cheers,
Nick.

--
Nick Coghlan | nc******@email. com | Brisbane, Australia
---------------------------------------------------------------
http://boredomandlaziness.skystorm.net
Jul 18 '05 #2
On 13 Jan 2005 20:36:19 -0800, "br********@gma il.com" <br********@gma il.com> wrote:
#
# My problem is that I want to create a
# class, but the variables aren't known
# all at once. So, I use a dictionary to
# store the values in temporarily. Why?# Then when I have a complete set, I want to
# init a class from that dictionary. Why do it that way?
# However, I don't want to specify the
# dictionary gets by hand
# since it is error prone.
# Thanks for any ideas, Brian
So I have a class defined that accepts a number of variables
# and they must be all present at object creation time. Why? Why not a method to check if it's valid yet, and then
add the attributes as they're available, without intermediaries.
You can make Test "smart" so it won't accept any other names than a,b,c
and will automatically convert to str, str, and int. Etc.

What are you actually doing? Is this a toy example of a more complex class?
class Test:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def __str__(self):
return '%s, %s, %d' % (self.a, self.b, self.c)

# For example:
t1 = Test('asd', 'sdf', 9)
print t1

# However, due to parsing XML, I am
# creating the values incrementally
# and I want to store them in a dictionary
# and then map them easily to a class Why store them in a dictionary? Why not create an empty Test instance,
and incrementally add the attributes directly as they're available?

What are you going to do with t1 and other instances?

dictionary = {}

# a mapping from source to destination
mapping = {
'a': str,
'b': str,
'c': int,
}

# a sample source of values
test_source = {
'a': 'test',
'b': 'asdf',
'c': 45
}

# now we go through and extract the values
# from our source and build the dictionary Just the three items in the test_source dictionary?
Is that just a 3-item holding place until you
for attr_name, function in mapping.items() :
dictionary[attr_name] = function(test_s ource.get(attr_ name))

print dictionary

# Here is the problem I want to avoid:
# Having to list the variable names
# as strings in multiple places. It is enought to
# have them in the 'mapping'
# dictionary above

t2 = Test(dictionary .get('a'), dictionary.get( 'b'),
dictionary.get ('c'))
print t2

Why don't you just let Test do all the work, and update it incrementally
until it is complete. You can use descriptors to manage state. You could
do any number of things. The main problem is defining the _requirements_
without premature implementation, never mind premature optimization ;-)

You may have good reasons for wanting to do what you seem to want to do,
but the picture is not clear to me ;-)

Regards,
Bengt Richter
Jul 18 '05 #3
Yes, my examle here is a tiny part of a larger more complex issue. My
application is an DOM XML parser that is reading attributes one at a
time. My class that I am creating is used elsewhere and must have
certain arguments for those uses to continue working. So, I seem to be
left with creating an intermediate object. Before, I was simply
creating an object:

t = Test()
for attr_name in mapping.keys():
setattr(t, attr_name, value_from_sour ce)

This I feel was ellegant, efficient and clear. However, what I have now
works but is not clear.
BTW, t1 is just for example and was just being printed
Thanks, Brian

Jul 18 '05 #4
On 14 Jan 2005 07:32:06 -0800, "br********@gma il.com" <br********@gma il.com> wrote:
Yes, my examle here is a tiny part of a larger more complex issue. My
application is an DOM XML parser that is reading attributes one at a you mean like <tag attname="value" att2="v2">blah blah</tag> and you are
grabbing things of interest out of a stream of info you are getting
from call-backs? Or the equivalent?time. My class that I am creating is used elsewhere and must have
certain arguments for those uses to continue working. So, I seem to be
left with creating an intermediate object. Before, I was simply Unless the "intermedia te object" accumulates information for multiple
Test() instances, why couldn't t= Test() be its own "intermedia te object"?

If you are accumulating info for multiple instances before creating them
it is not clear from your description.
creating an object:

t = Test()
for attr_name in mapping.keys():
setattr(t, attr_name, value_from_sour ce)

This I feel was ellegant, efficient and clear. However, what I have now
works but is not clear.
BTW, t1 is just for example and was just being printed


What about giving Test some methods to do what you'd like? E.g., a micro-step
in that direction from the above would let you write

t = Test()
...
t.load_info(inf osource)

Then the question becomes what infosource should be, or whether you really
need it at all. IOW, if you are doing infosource.add_ info(info_id, info_value)
why couldn't you do t.add_info(info _id, info_value), unless you have to
do t2.add_info(... ) alternately with t.add_info(...) , and if that's the case,
what is the criterion for choosing t vs t2? Maybe that could be done by something
that automatically manufactures t's as needed in a pool of partially complete t's.

But your real requirements are not clear enough here, so you may get help crossing
a stream, but no one will be able to say you are already on the side of the stream
you want to be later, and there's an easy path without need of crossing twice ;-)

Regards,
Bengt Richter
Jul 18 '05 #5

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

Similar topics

7
2192
by: Kerry Neilson | last post by:
Hi, Really hung up on this one. I'm trying to get all the fields of a dictionary to be unique for each class: class A { my_dict = dict_entry = { 'key1':0, 'key2':0 } __init__(self): for x in range(10):
50
6335
by: Dan Perl | last post by:
There is something with initializing mutable class attributes that I am struggling with. I'll use an example to explain: class Father: attr1=None # this is OK attr2= # this is wrong def foo(self, data): self.attr1=data self.attr2.append(data) The initialization of attr1 is obviously OK, all instances of Father redefine it in the method foo. But the initialization of attr2 is wrong
6
3185
by: Brian Jones | last post by:
I'm sure the solution may be obvious, but this problem is driving me mad. The following is my code: class a(object): mastervar = def __init__(self): print 'called a'
106
5530
by: A | last post by:
Hi, I have always been taught to use an inialization list for initialising data members of a class. I realize that initialsizing primitives and pointers use an inialization list is exactly the same as an assignment, but for class types it has a different effect - it calls the copy constructor. My question is when to not use an initalisation list for initialising data members of a class?
13
2363
by: Bryan Parkoff | last post by:
I have created three classes according to my own design. First class is called CMain. It is the Top Class. Second class and third class are called CMemory and CMPU. They are the sub-classes. Two sub-classes have the relationship to communicate back and forth through this pointer. The pointer is responsible inside Top class for allocating and deallocating two sub-classes. CMemory class is responsible to allocate and deallocate memory...
3
3485
by: J.J. Feminella | last post by:
(Please disregard the previous message; I accidentally sent it before it was completed.) I have source code similar to the following. public class Vehicle { protected string dataV; // ... more protected fields }
1
1676
by: Yue.Nicholas | last post by:
Hi, I have written a small prototype Python extension for a C-library. I have the methods all sorted out and it is working fine. In the C-library, they are various constants of types like string, integer, float and matrix. I'd like to expose them as READONLY values. Is the use of PyMemberDefs a suitable way to provide such access?
4
1764
by: Sunfire | last post by:
How do you make a collection inside a class and then access it? I am trying to make a class that is a news item and dont know where to really start. Any ideas?
5
1890
by: Andy B | last post by:
I am trying to figure out how to make an object instance available for all methods of a class. I tried to do something like this: public class test { TheObject Instance = new TheObject(); TheObject.Dictionary<string, string= new Dictionary<string, string>(); .... } The first line (TheObject instance = new TheObject();) doesn't get
0
8573
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8547
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8224
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
7013
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...
1
6062
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5517
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
4026
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...
1
2535
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
0
1393
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.