Using a Variable to Identify an Instance

Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
Reply

Join Date: Jan 2007
Posts: 1
Reputation: danielfolsom is an unknown quantity at this point 
Solved Threads: 0
danielfolsom danielfolsom is offline Offline
Newbie Poster

Using a Variable to Identify an Instance

 
0
  #1
Jan 19th, 2007
I'd like to set up something like this:
  1. a=0
  2. class b:
  3. def__init__(self, foo):
  4. self.foo = foo
  5. def create():
  6. global a
  7. a=a+1
  8. a=b("FOO")
Where the number 1 will define the instance (I'm not sure if define is the write word, whatever you put before the equals sign when your creating an instance)

The problem is, I can't. Obviously a would identify the instance instead of 1. I tried using dictionaries, but again the computer took it leterally - d{x} was the identity, not 1. Any suggestions?
[/code]
Reply With Quote Quick reply to this message  
Join Date: Jul 2006
Posts: 608
Reputation: jrcagle is on a distinguished road 
Solved Threads: 150
jrcagle jrcagle is offline Offline
Practically a Master Poster

Re: Using a Variable to Identify an Instance

 
0
  #2
Jan 19th, 2007
Originally Posted by danielfolsom View Post
I'd like to set up something like this:
  1. a=0
  2. class b:
  3. def__init__(self, foo):
  4. self.foo = foo
  5. def create():
  6. global a
  7. a=a+1
  8. a=b("FOO")
Where the number 1 will define the instance (I'm not sure if define is the write word, whatever you put before the equals sign when your creating an instance)

The problem is, I can't. Obviously a would identify the instance instead of 1. I tried using dictionaries, but again the computer took it leterally - d{x} was the identity, not 1. Any suggestions?
[/code]
Well, I'm a little confused. In this case, do you want to create an instance of class b with foo == 1?

If so, then you would do this:

  1. class b:
  2. def __init__(self, foo)
  3. self.foo = foo
  4.  
  5. a = b(foo=1) # Create instance of b class, assign it to a.

or even shorter,

  1. a = b(1) # Python will automagically assign self = b and foo = 1.
Some other thoughts:

(1) It's best to make all your classes the 'new style' class

class b(object): # this inherits from Python's 'object' base class

rather than

class b:

because it will allow things like public properties. You need something like Python 2.3 or higher to use new-style classes.

(2) By convention, class names are capitalized.

class B(object):

(3) Global variables are like garlic: best used sparingly.

Hope it helps,
Jeff
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:




Views: 1296 | Replies: 1
Thread Tools Search this Thread



Tag cloud for Python
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC