Calling class objects

Bernhard Herzog herzog at online.de
Sun Mar 5 20:10:53 CET 2000


Jp Calderone <exarkun at flashmail.com> writes:

> Here's a code segment I actually tested
> 
> class Master:
>         def startup(self, playerName):
>                 ## some init stuff, like get call the loadClass function
>                 ## a few times - this works, printing the results gives
>                 ## <class base.Player.Player at 80d2800>
>                 self.playerInitObj = self.loadClass(playerName)
> 
>         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
>                 self.player = self.playerInitObj(sock, addr)
> 
>         def loadClass(self, name):
>                 mod = __import__(name)
>                 return eval('mod.' + name)

getattr(mod, name) instead of eval would be better IMO

> 
>         def printStuff(self):
>             print 'Printing stuff'
> 
> if __name__ == '__main__':
>     m = Master()
>     m.startup('Master')
>     obj = m.playerInitObj()
>     print obj
>     obj.printStuff()
> 
> 
> The output of this code is
> 
> <Master.Master instance at 80c9c50>
> Traceback (innermost last):
>   File "Master.py", line 28, in ?
>     obj.printStuff()
> AttributeError: printStuff

If I take your code, save it as Master.py and run "python Master.py" I
get waht you'd expect:

<Master.Master instance at 80b5fb8>
Printing stuff

> Why is there an AttributeError when I try to call printStuff on
> a Master object?

My guess is that the Master module that actually is imported is not the
one you expect. One to find out which it actually is is to print
mod.__file__ in loadClass.

-- 
Bernhard Herzog   | Sketch, a drawing program for Unix
herzog at online.de  | http://sketch.sourceforge.net/



More information about the Python-list mailing list