Using polymorphism in the Python API¶
Illustrates polymorphism in the Python API.
In the Python API of CPLEX, the methods available to modify problem data are two-way polymorphic. That is, objects of a given type can appear as and be used like objects of another type. For example, to modify a single piece of data, you can call the method with a handle, such as the name or index of the variable, and the new data, like this:
>>> c.variables.set_upper_bounds("var0", 2.0)
>>> c.variables.get_upper_bounds("var0")
2.0
Likewise, to modify multiple pieces of data, you can call the method with a list of pairs of handles and data, like this:
>>> c.variables.set_upper_bounds([("var0", 3.0), ("var1", 4.0)])
>>> c.variables.get_upper_bounds("var0")
3.0
>>> c.variables.get_upper_bounds("var1")
4.0
Methods available to query problem data are four-way polymorphic. You can call them with a single handle, with two handles, with a list of handles, or with no handle at all. For example, the following line queries the upper bound of a given variable by name; that is, the method uses one argument.
>>> c.variables.get_upper_bounds("new_var")
3.0
The following example queries an inclusive range of data by calling the method with two handles (the first and last index) to return the upper bounds of all the variables in that range of indices.
>>> c.variables.get_upper_bounds(0, 3)
[1.0, 2.0, 1.0, 1.0]
As a third example of polymorphism, consider the following query by an arbitrary list of handles comprising two indices and a name. The method returns the upper bound of all those variables, whether they were called by index or by name.
>>> c.variables.get_upper_bounds([0, 1, "new_var"])
[1.0, 2.0, 3.0]
Indeed, you can query data by calling a method with no arguments at all. For example, the following line shows a query that returns a list equal in length to the number of variables.
>>> c.variables.get_upper_bounds()
[1.0, 2.0, 1.0, 1.0, . . ., 3.0]