473,560 Members | 2,953 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

using exec() to instantiate a new object.

Hello,

I'm trying to teach myself OOP to do a data project involving
hierarchical data structures.

I've come up with an analogy for testing involving objects for
continents, countries, and states where each object contains some
attributes one of which is a list of objects. E.g. a country will
contain an attribute population and another countries which is a list
of country objects. Anyways, here is what I came up with at first:

class continent(objec t):
def __init__(self,c ontinent_name):
self.name = continent_name
self.countries = []
def addCountry(self ,country_name):
self.countries. append(country_ name)
def listCountries(s elf):
for country in self.countries:
print country.name, "pop:",country. population,", states:"
country.listSta tes()

class country(object) :
def __init__(self,n ame):
self.name = name
self.population = 0
self.states = []
def addState(self,s tate_name):
self.states.app end(state_name)

def listStates(self ):
for state in self.states:
print " ",state.name,"p op:",state.popu lation
state.stateInfo ()

class state(object):
def __init__(self,s tate_name):
self.name = state_name
self.color = 'unknown'
self.counties = []
self.population = 0
def addCounty(self, county):
self.counties.a ppend(county)
def stateInfo(self) :
print " color:",self.co lor
print " counties",self. counties[:]
NAm = continent('NAm' )
usa= country('usa')
canada = country('canada ')
mexico = country('mexico ')
florida = state('florida' )
maine = state('maine')
california = state('californ ia')
quebec = state('quebec')

NAm.addCountry( usa)
NAm.addCountry( canada)
NAm.addCountry( mexico)
usa.addState(ma ine)
usa.addState(ca lifornia)
usa.addState(fl orida)
canada.addState (quebec)
florida.addCoun ty('dade')
florida.addCoun ty('broward')
maine.addCounty ('hancock')
california.addC ounty('marin')

florida.populat ion = 1000
california.popu lation = 2000
maine.populatio n = 500
quebec.populati on = 1000
florida.color = maine.color = california.colo r = 'blue'
NAm.listCountri es()

--------------------------------------------------------------------------
so this works but is far more cumbersome than it should be.
I would like to create an object when I add it

so I wouldn't have to do:
usa= country('usa')
NAm.addCountry( usa)

I could just do
NAm.addCountry( 'usa')

which would first create a country object then add it to a countries
list

to do this I tried:

def addCountry(self ,country_name):
# create an instance of country
exec(country_na me + "= country('" + country_name + "')")
# Add this new instance of a country to a list
exec("self.coun tries.append(" + country_name + ")")

Which doesn't give an error, but doesn't seem to create an instance of
the country object.

Does this make sense? Can this be done?
For my real project, I won't know the names and quantities of objects.
They will be highly variable and based on data contained in the
"parent" object.

Thanks
Nov 7 '08 #1
5 1364
On Fri, Nov 7, 2008 at 2:23 PM, RyanN <Ry*******@gmai l.comwrote:
>
to do this I tried:

def addCountry(self ,country_name):
# create an instance of country
exec(country_na me + "= country('" + country_name + "')")
# Add this new instance of a country to a list
exec("self.coun tries.append(" + country_name + ")")
Don't use exec. It's quite dangerous, and in your case is making
things much more complex than necessary. A much simpler way to do
what you want:

def addCountry(self ,country_name):
self.countries. append(country( country_name))

There is no need to bind the result of "country(countr y_name)" to a name at all.
Nov 8 '08 #2
On Nov 7, 4:23*pm, RyanN <Ryan.N...@gmai l.comwrote:
Hello,

I'm trying to teach myself OOP to do a data project involving
hierarchical data structures.

I've come up with an analogy for testing involving objects for
continents, countries, and states where each object contains some
attributes one of which is a list of objects. E.g. a country will
contain an attribute population and another countries which is a list
of country objects. Anyways, here is what I came up with at first:
snip
>
NAm = continent('NAm' )
usa= country('usa')
canada = country('canada ')
mexico = country('mexico ')
florida = state('florida' )
maine = state('maine')
california = state('californ ia')
quebec = state('quebec')

NAm.addCountry( usa)
NAm.addCountry( canada)
NAm.addCountry( mexico)
usa.addState(ma ine)
usa.addState(ca lifornia)
usa.addState(fl orida)
canada.addState (quebec)
florida.addCoun ty('dade')
florida.addCoun ty('broward')
maine.addCounty ('hancock')
california.addC ounty('marin')
snip
so this works but is far more cumbersome than it should be.
I would like to create an object when I add it

so I wouldn't have to do:
usa= country('usa')
NAm.addCountry( usa)

I could just do
NAm.addCountry( 'usa')

which would first create a country object then add it to a countries
list
snip

One option is to add the names to a blank object as attributes, using
setattr. Then you can access them in almost the same way... they're
just in their own namespace. Other options would be to add them to a
separate dictionary (name -object). This example is kind of cool,
as well as nicely instructive.
>>class Blank: pass
....
>>blank= Blank()
class autoname( ):
.... def __init__( self, name ):
.... setattr( blank, name, self )
.... self.name= name
....
>>autoname( 'fried' )
<__main__.auton ame instance at 0x00B44030>
>>autoname( 'green' )
<__main__.auton ame instance at 0x00B44148>
>>autoname( 'tomatoes' )
<__main__.auton ame instance at 0x00B44170>
>>blank.fried
<__main__.auton ame instance at 0x00B44030>
>>blank.green
<__main__.auton ame instance at 0x00B44148>
>>blank.tomatoe s
<__main__.auton ame instance at 0x00B44170>
>>blank
<__main__.Bla nk instance at 0x00B40FD0>

You don't have to call the container object 'blank', of course, or its
class for that matter. I do because that's how it starts out: blank.
Under the hood it's just a plain old dictionary with extra syntax for
accessing its contents.
Nov 8 '08 #3
Thank you both, I knew there had to be a good way of doing this.

-Ryan
Nov 10 '08 #4
On Nov 10, 7:47*am, RyanN wrote:
Thank you both, I knew there had to be a good way of doing this.

-Ryan
Just an update. I used dictionaries to hold objects and their names.
I'm beginning to understand better. Now to apply this to my actual
problem. Here's the code I ended up with:

class continent(objec t):
'''
A continent has a name and a dictionary of countries
'''
def __init__(self,c ontinent_name):
self.name = continent_name
self.countries = {} #countries is a dictionary of country name
and object
def addCountry(self ,country_name,p opulation = 0):
self.countries[country_name] = country(country _name) #Create a
new instance of country() and add it to dictionary
self.countries[country_name].population = population #Set
country population
def addState(self,c ountry_name,sta te_name,populat ion = 0):
if country_name in self.countries:

self.countries[country_name].addState(state _name,populatio n)
else: #This state must be in a new country
self.addCountry (country_name)
self.addState(c ountry_name,sta te_name,populat ion)
def listCountries(s elf):
for a_country in self.countries:
print a_country,
"pop:",self.cou ntries[a_country].population,", states:"
self.countries[a_country].listStates()

class country(object) :
'''
A country has a name, a population and a dictionary of states
'''
def __init__(self,n ame):
self.name = name
self.population = 0
self.states = {} #states is a dictionary of state name and
object
def addState(self,s tate_name,popul ation = 0):
self.states[state_name] = state(state_nam e) #Create a new
instance of state() and add it to dictionary
self.states[state_name].population = population
self.population += population #Add this state's population to
the country's

def listStates(self ):
#print self.states[:]
for a_state in self.states:
self.states[a_state].stateInfo()

class state(object):
'''
A state has a name, color, and a population
'''
def __init__(self,s tate_name):
self.name = state_name
self.color = 'unknown'
self.population = 0
def stateInfo(self) :
print " ",self.name,"po p:",self.popula tion,
"color:",self.c olor

#Now some examples of how to set and access this information
NAm = continent('NAm' ) #First we add our continent
NAm.addCountry( 'canada',700) #Now add a a country to NAm
NAm.addState('u sa','maine',400 ) #We can add a state even if we haven't
added the country yet
NAm.addState('u sa','california ',2000)
NAm.addState('c anada','quebec' ,700) # I know it's actually a province
NAm.addState('m exico','QR',550 )
usa = NAm.countries['usa'] # we can make things easier on ourselves
usa.population = 5000 #short for: NAm.countries['usa'].population =
5000
usa.addState('f lorida') #Another way to add a state, we can set
population seperately
NAm.countries['usa'].states['florida'].population = 2000
for any_state in usa.states: #Set an attribute for all state objects
usa.states[any_state].color = 'blue'
NAm.listCountri es() # Generates a report
# three ways to get to print the same information
print NAm.countries['usa'].states['maine'].name,
NAm.countries['usa'].states['maine'].population
print usa.states['maine'].name, usa.states['maine'].population # We
already assigned usa to NAm.countries['usa']
maine = usa.states['maine']
print maine.name, maine.populatio n
Nov 10 '08 #5
On Nov 10, 10:37*am, RyanN <Ryan.N...@gmai l.comwrote:
On Nov 10, 7:47*am, RyanN wrote:
Thank you both, I knew there had to be a good way of doing this.
-Ryan

Just an update. I used dictionaries to hold objects and their names.
I'm beginning to understand better. Now to apply this to my actual
problem. Here's the code I ended up with:
That's fine, but unless you add functionality that *does* actually
something with all these data, there's not much value going with an
OO approach compared to using plain old data structures (e.g.
[default]dicts and [named]tuples).

George
Nov 10 '08 #6

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

Similar topics

0
4541
by: Phil Powell | last post by:
I traced the problem to what I believe is when I use the included content library script into the viewinterns.php page. This script will repeatedly instantiate a DateGroupHTMLGenerator class because I have to constantly produce these HTML form element fields with different names throughout my page. Here is the code I use to reproduce it...
4
2050
by: Michael Sparks | last post by:
Anyway... At Europython Guido discussed with everyone the outstanding issue with decorators and there was a clear majority in favour of having them, which was good. From where I was sitting it looked like about 20:20 split on the following syntaxes: 1 def func(arg1, arg2, arg3) : function... 2 def func(arg1, arg2, arg3):...
5
3493
by: gilles27 | last post by:
I've ready many of the posts on this and other newsgroups in which people describe working practices for source control of database scripts. We are looking to implement something similar in my current workplace. We have agreed that developers should not modify objects such as views or stored procedures directly, they should check the script...
2
22052
by: Prashant | last post by:
Hi , Need some help ! . I am storing Classnames in an XML file and depending on the user's choice of process want to : 1) Read the classname of that process from the XML file 2) Instantiate an object of that class from the string received from the XML (which is the classname)
3
2147
by: Khurram | last post by:
Hi, I am trying to use Crystal Reports with ASP.NET. I created a dataset and tried to display it in the report but nothing came up. I did not get an exception either. I know that the dataset is populated so it has to be a very basic binding issue. To bind the report object to dataset I called the SetDataSource method of Report object...
1
2831
by: learning | last post by:
Hi how can I instaltiate a class and call its method. the class has non default constructor. all examples i see only with class of defatul constructor. I am trying to pull the unit test out from the product source code, but still want to execute them under nunit. I am trying this idea on nunit sample source code. Here is my class and the...
5
2285
by: =?Utf-8?B?dmlzaHJ1dGg=?= | last post by:
This code works fine in Windows Application. In Windows Application, I am able to zip the image files properly and it totally contains 900MB My problem is the same code which I used in my Windows Application, does not work while I run it with Windows services. In my Windows application I am able to zip the whole 900Mb without any problems,...
2
1640
by: Danny Shevitz | last post by:
Howdy, In my app I need to exec user text that defines a function. I want this function to unpickle an object. Pickle breaks because it is looking for the object definition that isn't in the calling namespace. I have mocked up a simple example that shows the problem. Run this first code (from create_pickle.py) to create the pickle. ...
0
1773
by: Chris Rebert | last post by:
On Fri, Nov 14, 2008 at 10:40 AM, Indian <write2abdul@gmail.comwrote: You don't need and shouldn't be using `exec` here. It appears as though you're just doing the following in a much more obtuse and unnecessarily complicated manner: def OpenKey(rootkey, path, reg): open_key = reg for key in path.split('\\'): open_key = open_key
0
7632
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...
0
7841
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. ...
0
8066
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...
1
7596
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...
0
6191
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...
0
3585
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2047
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
1
1169
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
877
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...

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.