a basic question- how to create a instance using a variable?

Hi! I have had this particular problem in my “old short” C++ days and I am having it again…

How can I create a instance of a class/object using a variable?

example (how I think it “should” work)

class ClassName(DirectObject)
def something:
do something

def somethingother:
do something other

def createInstance(instanceName):
instanceName=ClassName() <== Thats what is not working
instanceName.something() <== needs to be the correct Instance

createInstance(instance1)
createInstance(instance2)

instance1.somethingother
instance2.something

In short words: How do I call an instance with the help of an variable?
I used a dict for that, but that does the same like a normal variable does… it removes its value when called like

dict{‘InstanceName’ : ‘instance1’}
dict[‘InstanceName’]=ClassName()
and replaces ‘instance1’ with a pointer to the class to ClassName.

If Python is a Object based scripting language it should be possible to ask for a object using a variable… - the question is: how?

Regards, Bigfoot29

I’m not sure if I understand you correctly, but I think you want to asign an object to a variable?

Your example code wouldnt work, should look like this:


class Example(DirectObject):

    def __init__(msg): 
        self.msg = msg

    def showMsg(self):
        print self.msg

instance1 = Example("Hello Instance 1")
instance2 = Example("Hello Instance 2")

instance1.showMsg()
instance2.showMsg()

No I mean the other way around…
I want to call the instance USING a variable.

lets say I have a client connecting to a server. The server is getting a connection and the client is authing with its USERNAME (billy, bob, yellow, …) and its password. I want to create an object with the object name USERNAME (I do not want the object have an attribute name that contains the USERNAME, I want to create an instance of the object like this:

USERNAME=Client()
where Client() is the original class where I want to create the instance from. - I didn’t want to be that specific. Thats why I asked in a more general way.

In the result I want to pass variables or messages to the objects like
bob.getAdress()
billy.setAge(18)
yellow.isOnline(1)
bigfoot29.chat(MSg from Billy: Yellow didn’t understand your first Post here)

(last example would then send the msg directly to my client connected to the server through the instance of the client class at the server that gets the message from Billy and passes it to my client.)

I know its not that easy to declare… but its a simple problem where I haven’t got a solution for.

Regards, Bigfoot29

well, the only way I can think of is by looking up the correct object through a dictionary, other then that I dont think its posible. Neither do I understand how that would be desireable though…

So here is what I have for you, IPKnightly helped me with the dicts

class Example:
	def __init__(self,msg):
		self.msg = msg
	
	def showMsg(self):
		print self.msg

class MyContainer:
	def __init__(self):
		self.items= {}
	
	def __getitem__(self,name):
		return self.items[name]
	
	def addnewitem(self,name):
		self.items[name]= Example("I am " + name)

c= MyContainer()
c.addnewitem("Martin")
c.addnewitem("David")

c["Martin"].showMsg()

Hope this is comes usefull for you

Regards Martin

Ah… exactly that way :smiley:

Thanks!

I guess later on I need something that is no dictionary to do the task, but for NOW this is a great way to do it.

As said… Thanks again.

Regards, Bigfoot29

If I know a betterway I will inform you.
The Container is providing you the acces an you can change what its making without changing your full code.

But I think dicts are the best way to do what you want to do

Martin

Thank you Martin… atm its working as supposed to do :slight_smile:

Here the code in completeness (not complete, but showing every aspect of how I would want to use it:

# Just created a dict for that cuz we worked with dicts much lately... of course this is
# just one way how you can feed the supervisor with variables he can work with...
users={
        0 : 'Klaus',
        1 : 'Martin'
        }


# Code provided by Martin/IPKnightly - nearly unchanged
class Client:
        def __init__(self, message='text'):
                self.msg=message

        def showMsg(self):
                print self.msg

        # Just a method to overwrite the initially given msg.
        def setNewMessage(self, message='text'):
                self.msg=message

class Container:
        def __init__(self):
                self.items= {}

        #guess you guys are overloading a method?
        def __getitem__(self, name='text'):
                return self.items[name]

        def addNewItem(self, name='text', msgForClient='text'):
                self.items[name]= Client(msgForClient)

        #Just for my use and to not get confused between client and items       
        def addNewClient(self, name='text', msgForClient='text'):
                self.addNewItem(name, msgForClient)

# for initialization of the supervisor
supervisor= Container()

# just a example how I want to create the instances using a dict in this example
# of course anything else can be used here. Its simple, yes, but we are using VARIABLES.
i=0
while i<2:
        supervisor.addNewClient(users[i], 'default text')
        i=i+1

# show me that its working...

i=0
while i<2:
        supervisor[users[i]].showMsg()
        i=i+1

# And now lets test if we can adress everything as it should work.

supervisor['Martin'].setNewMessage('Hi! Its me, Martin!')

supervisor[users[1]].showMsg()

Plus the output:

 ppython instances.py 
default text
default text
Hi! Its me, Martin!

Again, thanks for your help, guys… maybe other ppl will find this usefull too :smiley:

Regards, Bigfoot29