DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   Python (http://www.daniweb.com/forums/forum114.html)
-   -   Using a Variable to Identify an Instance (http://www.daniweb.com/forums/thread67801.html)

danielfolsom Jan 19th, 2007 12:25 pm
Using a Variable to Identify an Instance
 
I'd like to set up something like this:
a=0
class b:
 def__init__(self, foo):
  self.foo = foo
def create():
 global a
 a=a+1
 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]

jrcagle Jan 19th, 2007 7:58 pm
Re: Using a Variable to Identify an Instance
 
Quote:

Originally Posted by danielfolsom (Post 303461)
I'd like to set up something like this:
a=0
class b:
 def__init__(self, foo):
  self.foo = foo
def create():
 global a
 a=a+1
 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:

class b:
  def __init__(self, foo)
      self.foo = foo

a = b(foo=1)  # Create instance of b class, assign it to a.

or even shorter,

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


All times are GMT -4. The time now is 5:59 am.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC