首页 > 解决方案 > 如何在类之外打印变量?

问题描述

我对 Python 很陌生。我目前正在使用 Jupyter Notebook,我需要在以下类之外打印变量“pos_best_g”:

class PSO():
    def __init__(self,costFunc,x0,bounds,num_particles,maxiter):
        global num_dimensions

        num_dimensions=len(x0)
        err_best_g=-1                   # best error for group
        pos_best_g=[]                   # best position for group

        # establish the swarm
        swarm=[]
        for i in range(0,num_particles):
            swarm.append(Particle(x0))

        # begin optimization loop
        i=0
        while i < maxiter:
            #print i,err_best_g
            # cycle through particles in swarm and evaluate fitness
            for j in range(0,num_particles):
                swarm[j].evaluate(costFunc)

                # determine if current particle is the best (globally)
                if swarm[j].err_i < err_best_g or err_best_g == -1:
                    pos_best_g=list(swarm[j].position_i)
                    err_best_g=float(swarm[j].err_i)

            # cycle through swarm and update velocities and position
            for j in range(0,num_particles):
                swarm[j].update_velocity(pos_best_g)
                swarm[j].update_position(bounds)
            i+=1

        # print final results
        print ('FINAL:')
        print (pos_best_g)
        print (err_best_g)

initial=[5,5,5,5,5]               # initial starting location [x1,x2...]
bounds=[(-10,10),(-10,10),(-10,10),(-10,10),(-10,10)]  # input bounds [(x1_min,x1_max),(x2_min,x2_max)...]
PSO(func1,initial,bounds,num_particles=15,maxiter=30)

目前我得到以下结果:

FINAL:
[4.999187204673611, 5.992158863901226, 4.614395966906296, 0.7676323454298957, 8.533876878259441]
0.001554888332705297

但是,我不知道如何提取结果,因为它们都在 In[] 单元格而不是 Out[] 单元格中。

我需要做什么才能启用此功能?

非常感谢

标签: pythonclass

解决方案


我猜这是你自己定义的类,对吧?您可以尝试添加一个 getter 方法,然后在 Jupyter notebook 中调用此方法以将输出结果存储在变量中,如下所示:

只需在您的课程中包含这些小功能

def get_pos_best(self):
   return self.pos_best_g

def get_err_best(self):
   return self.err_best_g

现在,在您的笔记本中执行以下操作:

object_PSO = PSO(costFunc,x0,bounds,num_particles,maxiter)
list_you_want = object_PSO.get_pos_best()
error_you_want = object_PSO.get_err_best()

祝你好运!


推荐阅读