Calling class objects

Gordon McMillan gmcm at hypernet.com
Sun Mar 5 08:27:48 EST 2000


Jp Calderone <exarkun at flashmail.com> wrote:

>class Master:
>        def __init__(self):
>                ## some init stuff, like get call the loadClass function
>                ## a few times - this works, printing the results gives
>                ## <class base.Player.Player at 80d2800>
>                playerInitObj = loadClass('Player')
>
>        def connectionMade(self, sock, addr):
>                ## Call the constructor with sock and addr
>                ## This is where it seems to die - CPU usage jumps
>                ## to 100% and the network code stops accepting connections
>                ## - presumably because it is blocking on this call
>                player = playerInitObj(sock, addr)
>
>        def loadClass(name):
>                mod = __import__(name)
>                return eval(name + '.' + name)


>So why doesn't the connectionMade function do what I think it should?

It's difficult to figure out what you think it should do. My guess is this:

import Player
class Master:
  def __init__(self):
    self.playerInitObj = Player.Player()
  def connectionMade(self, sock, addr):
    self.player = self.playerInitObj(sock, addr)

Your Master.__init__ can't possibly work unless you have a global function 
"loadClass" (as written above you'd get a NameError). However, even if it 
did work, it would assign the results of loadClass to a method-local var which 
goes out of scope and gets deleted on the next line. Master.connectionMade 
has the exact same problem.

Because Python does not require variables to be declared, you must explicitly 
use "self" to make a variable belong to the instance.

Since you've hardcoded "Player", I don't see the reason for the dynamic 
import. If you don't want the Player module imported until it's needed, use:

  def __init__(self):
    import Player
    self.playerInitObj = Player.Player()

This has the additional advantage that the second instance of Master won't 
incur the overhead of searching your disk for a module named "Player".




More information about the Python-list mailing list