tags:

views:

67

answers:

3

I have the following Bird definition:

class Bird:
    def __init__(self, swarm, position = None):
        if (swarm == None):
            raise ValueError("swarm variable should not be None!")

        if (not(type(swarm)).__name__ == 'ParticleSwarmOptimization'):
            raise TypeError("swarm variable must be of type ParticleSwarmOptimization!")

It is raising error in the last line. In the interpreter it prints:

(type(swarm)).__name__
'instance'

I'd expect it to print "ParticleSwarmOptimization". I'm calling Bird's constructor the following way:

def AddBird(self, position = None):
    self.birds += Bird(self, position)

With this I want that every bird has a reference to the main ParticleSwarmOptimization class, and I want to ensure that every time a Bird is created I have in fact a ParticleSwarmOptimization instance reference and not anything else.

Thanks!

+3  A: 

use:

assert isinstance(swarm, ParticleSwarmOptimization)

The culture of Python is to not do these sorts of defensive checks, instead to simply use the variable. If it is of the wrong type, an exception will eventually be raised.

Ned Batchelder
A: 

try using

isinstance

instead.

aaa
+3  A: 

Other people have mentioned the correct way to do this, however the reason you get that error is because you are using an old style class. To get a new-style class make your classes subclass object.

Alex Gaynor
+1 for recommending new-style classes, they fix so many issues of old style ones (including this tiny one;-). Though as everybody's saying `isinstance` is still a better idea here;-).
Alex Martelli