I think that @cbloom8‘s theory is a good one. Not that there aren’t other explanations, as well.
I think it can be a form of cognitive dissonance. That is, you might feel so bad inside, but there are no external conditions in your life that warrant feeling this bad. Therefore you need to punish yourself in order to make things equal. Well… I suppose you could try to eliminate the bad feelings to make things equal, but most people try that and fail, so that leaves the other choice as the only workable one.
Somehow, when you are in psychic or emotional pain, physical pain just feels right. When people mourn, they often tear at their clothes and thrash about, and do other things that might physically hurt them. Devouts used to go around beating themselves with whips or wearing things that would cut them and make them bleed. I think these kinds of pursuits held a natural appeal for depressives who feel responsible for the world and utterly inadequate to do anything to help it. Thus, they punish themselves for failing to do what their life’s mission is.
There is something about feeling pain, or perhaps even better, seeing the blood flow that is satisfying. It gives meaning to the pain. It justifies it. It releases you a bit. I’m just imagining this here. When I was depressed, I wanted to punish myself. I didn’t care if I got hurt. I wanted for there to be a reason why I was suffering. I didn’t cut myself, but I think I considered doing it or something like it. One thing I did was to scratch myself until I bled. That was very satisfying, somehow.