SystemVerilog for Verification: A Guide to Learning the Testbench Language Features

A class can contain multiple constraint blocks. Your class might naturally divide into two sets of variables, such as data vs. control, so you may want to constrain them separately. Or you might want to have a separate constraint for each test. Perhaps one constraint would restrict the data length to create small transactions (great for testing congestion), while another would make long transactions.
At run-time, you can use the constraint_mode() routine to turn constraints on and off. When used with handle.constraint, this method controls a single constraint. When used with just handle, it controls all constraints for an object.
class Packet; rand int length; constraint c_short {length inside {[1:32]}; } constraint c_long {length inside {[1000:1023]}; }endclassPacket p;initial begin p = new; // Create a long packet by disabling short constraint p.c_short.constraint_mode(0); assert (p.randomize()); transmit(p); // Create a short packet by disabling all constraints // then enabling only the short constraint p.constraint_mode(0); p.c_short.constraint_mode(1); assert (p.randomize()); transmit(p);end