You can paint trim either before or after installation. If you paint it before installation to prevent spills or messes, you will still need to touch up holes afterward where you attached it to the wall. Many people choose to paint their walls before installing trim.
If you're installing carpet, you should paint the baseboards and let them dry beforehand. However, it's easier to install carpet without baseboards, so if you're installing new trim and carpet, it may be simpler to do the carpet first.