python - 如何在类之外打印变量?
问题描述
我对 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[] 单元格中。
我需要做什么才能启用此功能?
非常感谢
解决方案
我猜这是你自己定义的类,对吧?您可以尝试添加一个 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()
祝你好运!
推荐阅读
- python - Django中敏感数据的加密模型字段
- javascript - 无法在 Django 中传递字典
- node.js - 升级 Node.js 时的 SequelizeConnectionError(4x 到 7x)
- mysql - vb.net - 基于任务的 SQL 类“一个一个”地处理 SQL 查询
- azure-application-insights - 由于 AppInsights,Azure ML 管道运行缓慢
- quill - Quill - 如何根据单词/字符长度将 Delta 分割成段?
- html - 将 CSS 连接到 HTML 时遇到问题
- vba - 使用批处理文件运行 MS 访问模块时找不到对象错误的原因是什么?
- python - Pandas - 日期时间列的奇怪问题
- excel - Excel将按钮变成图像