most of these chips support "ICSP", basically a serial connection designed to be used when the chip is "in circuit". sometimes its a plug & socket, the 3x2 one on the Arduino boards for example, on boards this size its usually five or so exposed copper pads. it goes into a housing, a lid is shut and pins contact those pads (note you couldn't do this inside a loco). that will provide power, ground, a two wire serial interface and a reset connection. the pins will be put into a specific state as it powers up and it goes into programming mode - data is loaded then the reset triggered. depending on the code and the chip it can also be verified by reading it back.
some of the programmers are simple, e.g. you can use an arduino to programme some of them, others need their own programmers - which is why I don't play with PIC stuff here, sodding expensive
real killer though is needing the code to flash it with, invariably kept reasonably well guided. indeed some of these chips in the programmer can have a fuse blown which disables the programming port to stop people reading it back