Phillipe Pépin
Phillipe Pépin

Reputation: 47

Print the return of a method in python

I'm fairly new to OOP in python and i cant seem to figure out if I'm doing this the right way. I have a first script called TP2_dat.py in which I solve a problem in AMPL and then at the end i retrieve the variable X as follows (I simplified the code):

import amplpy
import os

class Solver:

    def __init__(self, set_k, larg_on, poids):

        self.set_K = set_k
        self.larg_on = larg_on
        self.poids = poids

    def solve(self):

        ...

        X = ampl.getVariable('X')
        X_val = X.getValues()
        X_val_dic = X_val.toDict()

        # print(X_val_dic)
        return X_val_dic

I tried to do a print instead of a return from the first script and it worked. But now i want to print it from another script as follows so i dont get the None at the end of the print from the second script:

from TP2_dat import Solver

set_K = [1,2,3,4,5,6]
larg_on = [4,3,5,4,6,5]
poids = [0,4,5,2,3,6,4,0,4,3,5,3,5,4,0,4,7,8,2,3,4,0,3,3,3,5,7,3,0,5,6,3,8,3,5,0]

affichage = Solver(set_K, larg_on, poids)

affichage.solve()
print(X_val_dic)

The part that i dont understand is can i do something similar to this? Am i right in thinking to return the value of X_val_dic or should i do something else?

Thanks a lot for your help !!

Upvotes: 1

Views: 48

Answers (1)

Wamadahama
Wamadahama

Reputation: 1648

Since the class method solve returns a value you need to set it equal to a variable or print it directly:

X_val_dic = affichage.solve()
print(X_val_dic)

or

print(affichage.solve())

See this article for more information on pythons variable scoping.

Upvotes: 6

Related Questions