Skip to main content
 首页 » 编程设计

python之如何在方法中传递实例的引用

2025年05月04日11kerrycode

我有以下 Bird 定义:

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!") 

它在最后一行引发错误。在解释器中打印:

(type(swarm)).__name__ 
'instance' 

我希望它打印“ParticleSwarmOptimization”。 我通过以下方式调用 Bird 的构造函数:

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

有了这个,我希望每只鸟都有对主要 ParticleSwarmOptimization 类的引用,并且我想确保每次创建鸟时我实际上都有一个 ParticleSwarmOptimization 实例引用,而不是其他任何东西。

谢谢!

请您参考如下方法:

使用:

assert isinstance(swarm, ParticleSwarmOptimization) 

Python 的文化是不进行这些类型的防御性检查,而是简单地使用变量。如果类型错误,最终会引发异常。