Discover instance variables
JonathanB
doulos05 at gmail.com
Mon Jul 16 16:42:21 EDT 2007
> > class Foo():
> > self.a = "bar"
> > self.z = "test"
> > self.var = 2
>
> That's unlikely to work, though: the code is in the context of the
> class, not one of its methods, so unless you happen to be declaring a
> class inside another class's method it's unlikely that there's going to
> be a "self" around when those three lines execute.
Ah, I see. Trouble is I write most of my code on a computer that
doesn't have python (shared computer and I don't have permissions to
install). So I code it here, email it to myself, and test it at home.
I had my debugged code at home so I couldn't post a working example.
Here's working example.
class World():
def __init__(self, name, WTN, Ag, Na, Ex, In, Ni, Al, Port, Type,
Dia, Grav, Atmosphere, Hyd, Climate, Pop, Gov, CR, TL, Wealth,
Trade=None, notes=None):
self.name = name
self.WTN = WTN
self.Ag = Ag
self.Na = Na
self.Ex = Ex
self.In = In
self.Ni = Ni
self.Al = Al
self.Port = Port
self.Trade = Trade
self.Type = Type
self.Dia = Dia
self.Grav = Grav
self.Atmosphere = Atmosphere
self.Hyd = Hyd
self.Climate = Climate
self.Pop = Pop
self.Gov = Gov
self.CR = CR
self.TL = TL
self.Wealth = Wealth
self.notes = notes
The code to execute this is:
def world_info():
# code to prompt for each variable
world = World(name, WTN, Ag, Na, Ex, In, Ni, Al, Port, Type, Dia,
Grav, Atmosphere, Hyd, Climate, Pop, Gov, CR, TL, Wealth)
So given that example, is there a clean way to get this output:
Data for Earth:
Name = Earth
WTN = 5.0
Ag = 0
Na = 0
...
...
Notes = None
> [name for name in dir(x) if not callable(name) and not
> name.startswith("__")]
That does looks almost exactly like what I want I think (I'm still
learning to read code to learn what it does, but from what it looks
like this does a list comprehension that removes everything callable
and that starts with "__")
> [name for name in dir(x) if not callable(name) and not
> name.startswith("__")]
>
> might come close - I presume you don't want __doc__ and the like.
>
More information about the Python-list
mailing list