首页 > 解决方案 > 如何修复我的类代码“int”对象错误?

问题描述

class Rbox:
    """ Defining a class """
    def __init__(self,num_parts=100):
        self.num_parts=num_parts
        self.list_particles=[0]*num_parts    
    def get_left_count(self):
        print("the number of particles on the left: "+str(self.list_particles.count(0)))
        return self.list_particles.count(0)      
    def get_right_count(self):
        print("The number of particles on the right is: "+str(self.list_particles.count(1)))
        return(self.list_particles.count(1))
    def run_sim(self,time=1000):
        for i in range(time):
            var=int(random.random())*(self.num_parts)
            if self.list_particles[var]==0:
                self.list_particles[var]=1
            if self.list_particles[var]==1:
                self.list_particles[var]=0

我正在尝试运行这条线Rbox.run_sim(10)以运行一个通过随机过程将粒子从左侧盒子移动到右侧盒子的过程。但我不断收到错误'int' object has no attribute 'num_parts'。我不确定如何解决此错误?

标签: pythonclassobjectmethods

解决方案


看来你还没有初始化这个类。尝试

rbox = Rbox()
rbox.run_sim(10)

推荐阅读