An Object-Oriented Primer in Python: Part 1
I’ve read several tutorials on Object-Oriented Programming (OOP), and none of them has been as clear as I thought they should be. So it took me a long time to figure out OOP, and now I feel like I should pass on the knowledge. Here it is:
Objects
One of the main difficulties in OOP is thinking about it. So start trying to wrap your mind around an object. Basically, an object is a specialized data structure than can hold information, and do things with it. In other words, it’s a thing represented by code. And you aren’t limited to just one thing, you can have as many as you want, just as you can have as many numbers, lists or dictionaries as you want.
Holding Information and Doing Things
You can give objects attributes. What’s even cooler is that you can access them really specifically:
fido = Dog("Golden Retriever")
fido.breed
Assuming you’ve made a “Dog” class, fido.breed will be a string saying “Golden Retriever.” You can also change the data (it’d be pretty pointless if you couldn’t…) :
>>> fido = Dog("Golden Retriever")
>>> fido.showBreed()
It's a Golden Retriever
>>> fido.breed = "Labrador"
>>> fido.showBreed()
It's a Labrador
>>> fido.changeBreed("Dalmatian")
>>> fido.showBreed()
It's a Dalmatian
>>> fido.breed
'Dalmatian'
Here we make a Golden Retriever named fido. We have it call a method (OOP-speak for function) to say what breed it is, and then change it’s breed variable to “Labrador.” After that, we use a different method (yes, objects can have multiple methods) to change the breed to “Dalmatian,” and have fido tell us that he is, in fact, a Dalmatian. If you feel like having to prefix everything with “fido.” is annoying, don’t worry: There’s a reason. We could just as easily have:
>>> fido = Dog("Golden Retriever")
>>> spot = Dog("Mutt")
>>> fido.showBreed()
It's a Golden Retriever
>>> spot.showBreed()
It's a Mutt
If we just used a generic ’showBreed()’ method, Python wouldn’t know whether we were talking about fido or spot, or some other dog. The <name><dot> system is a pretty efficient way of telling Python who’s doing what, or who’s remembering what.
Look back over this section and make sure you understand it well: We made an instance of the Dog class, which held information (fido.breed) and did things (fido.showBreed()), we also made another instance of the same Dog class (spot), which held different, but similar information (Mutt instead of Golden Retriever), and did similar things (said what breed he, spot, was, as opposed to what fido was).
Obviously stuff can get a lot more complicated, but if you understand that, you’re doing fine!
~Read Part 2 to learn how to make classes~


















































