The reasons for it are complex. Vaughn Bell1 refers to a study that looks at various motivations for these behaviours; he also provides some of the illustrative examples given in the article.
To me, the important point he makes is that too many health professionals think that self-harm is done merely as a way of gaining attention, which is unhelpful. If this is true of those practitioners then it might be true of some of us too.
See The complex motivations for self-harm.