473,805 Members | 1,949 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

help needed with class and method confusion

First I am sorry for the title but I an newbie enough to now know how to better
word it.

The problem part of my code is
class Application:
class Moon:
def __init__(self, name):
self.name = name
def __init__(self):
self.moons = []
names = ["Io", "Europa", "Ganymeade"]
for name in names:
setattr(self, name, Moon(name))
I would like to somehow get self.moons to equal
[self.Io, self.Europa, self.Ganymeade]. I had hoped on using
self.moons as an iterant in "for" loops to be able to alter each
in turn.

Thanks in advance for any possible help.
Jul 18 '05 #1
3 1154
"Cndistin" <cn******@aol.c om> wrote in message
news:20******** *************** ****@mb-m01.aol.com...
The problem part of my code is
class Application:
class Moon:
def __init__(self, name):
self.name = name
def __init__(self):
self.moons = []
names = ["Io", "Europa", "Ganymeade"]
for name in names:
setattr(self, name, Moon(name))
I would like to somehow get self.moons to equal
[self.Io, self.Europa, self.Ganymeade]. I had hoped on using
self.moons as an iterant in "for" loops to be able to alter each
in turn.

Thanks in advance for any possible help.


class Application:
class Moon:
def __init__(self, name):
self.name = name
def __repr__(self):
"added this to pretty up the printing of a.moons"
return "Moon(%s)"%self .name

def __init__(self):
self.moons = []
names = ["Io", "Europa", "Ganymeade"]
for name in names:
# took Moon(name) out of the setattr() because we'll be
# using it again in moons.append. Also used self.Moon
# because Moon alone raises a NameError
moon = self.Moon(name)
setattr(self, name, moon)
self.moons.appe nd(moon)

a = Application()
print a.moons

# output
[Moon(Io), Moon(Europa), Moon(Ganymeade)]

HTH
Sean
Jul 18 '05 #2
Here's one way to do it (undoubtedly there are other ways as well).
Sorry, I couldn't loop the moons. Probably a programmer more clever
than I could write a factory pattern for it.

class Moon:
def __init__(self, name, diameter = 0.0, planet = "unknown"):
self.NAME = name
self.DIAMETER = diameter
self.HOMEPLANET = planet

def setMoonName(sel f, name):
self.NAME = str(name)

def getMoonName(sel f):
return self.NAME

def setMoonDiameter (self, diam):
self.DIAMETER = float(diam)

def getMoonDiameter (self):
return self.DIAMETER

def setMoonHomePlan et(self, planet):
self.HOMEPLANET = str(planet)

def getMoonHomePlan et(self):
return self.HOMEPLANET
if __name__ == "__main__":
moons = []
Io = Moon("Io", 1.0, "Jupiter")
moons.append(Io )
Europa = Moon("Europa", 2.0, "Jupiter")
moons.append(Eu ropa)
Ganymeade = Moon("Ganymeade ", 3.0, "Jupiter")
moons.append(Ga nymeade)
Titan = Moon("Titan", 3.0, "Saturn")
moons.append(Ti tan)

for x in range(len(moons )):
print moons[x].getMoonName()
print moons[x].getMoonDiamete r()
print moons[x].getMoonHomePla net()
print
Jul 18 '05 #3
If I understand the problem, you have a planet and a number of moons turning
around it. So you should define two different classes, Planet and Moon

--------------------------------
class Moon:

def __init__(self, name):
self.name = name

class Planet:

def __init__(self,n ames):
self.moons = []
for name in names:
m=Moon(name)
setattr(self, name, m)
self.moons.appe nd(m)

satellites = ["Io", "Europa", "Ganymeade"]
Jupiter = Planet(satellit es)
-------------------------------

You'd better leave the satellite names outside of the __init__ method of
Planet,
in case you happen to work on another planet

Hope this helps,
Pierre
Jul 18 '05 #4

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

Similar topics

18
6962
by: John M. Gabriele | last post by:
I've done some C++ and Java in the past, and have recently learned a fair amount of Python. One thing I still really don't get though is the difference between class methods and instance methods. I guess I'll try to narrow it down to a few specific questions, but any further input offered on the subject is greatly appreciated: 1. Are all of my class's methods supposed to take 'self' as their first arg? 2. Am I then supposed to call...
5
2398
by: MFC | last post by:
Ok, after three C# books, (C# How to Program, Programming in the Key of C#, and C# Weekend Crash Course) and three weeks, I believe I have tried everything to make a certain form function correctly. I am trying to learn C# after playing around for a bit with procedural programming with PHP, not OOP, and believe I have learned quite a bit in three weeks, just not enough to accomplish this one task. If anyone has a bit of free time and...
3
3719
by: Dan Trowbridge | last post by:
Hi everyone, In my attempt to port code from VS 6.0 to VS.NET I had some code break along the way, mostly due to not adhereing closely to the C++ standard. This may be another instance but I can't think of a good fix, or even why it broke. The problem In one of my CFormView derived classes I have a member variable of the type...
5
3600
by: serge calderara | last post by:
Dear all, I am new in asp.net and prepare myself for exam I still have dificulties to understand the difference between server control and HTML control. Okey things whcih are clear are the fact that for server control component , code is running on the server side. But if I take as example a Label. I place on a webform an HTM label control and a WebForm label control, I could see that properties are different for
55
3340
by: Sam | last post by:
Hi, I have a serious issue using multithreading. A sample application showing my issue can be downloaded here: http://graphicsxp.free.fr/WindowsApplication11.zip The problem is that I need to call operations on Controls from a delegate, otherwise it does not work. However each time I've done an operation, I must update the progressbar and progresslabel, but this cannot be done in the delegate as it does not work.
2
1655
by: Anup Daware | last post by:
Hi Group, I have a little confusion over the use of static class in C#. I have a static method in my static class. This method reads an xml and returns a collection of objects. This collection of objects can be different for different users. This method uses some non-static variables which are local to this method. Following is my static class:
2
2907
by: rookiejavadude | last post by:
I'm have most of my java script done but can not figure out how to add a few buttons. I need to add a delete and add buttong to my existing java program. Not sure were to add it on how. Can anyone help? my script is below. thank you import java.awt.*; //import all java.awt import java.awt.event.*; //import all java.awt.event import java.util.*; //import all java.util import javax.swing.*; //import all javax.swing class Product...
4
1141
by: yadin | last post by:
class big(self): x = 32 list = def inside (self): class small(self): # a new class defined inside the first y = 348 list.append(y) # send the value to first list
32
2799
by: =?Utf-8?B?U2l2?= | last post by:
I have a form that I programmatically generate some check boxes and labels on. Later on when I want to draw the form with different data I want to clear the previously created items and then put some new ones on. In my code I am doing the following: For Each ctrl In tpMain.Controls If TypeOf (ctrl) Is CheckBox Then If ctrl.Name.StartsWith("chkS") Then ctrl.Visible = False
0
9596
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10607
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
10359
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
10364
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
6875
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
5541
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
5677
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3843
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3007
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.