Python Programming for the Absolute Beginner, 3rd Edition
OOP has a reputation for being complicated, but I think it's actually simpler than some of the concepts you've already learned. In fact, OOP allows you to represent things in your programs in a way that's more like the real world.
What you often want to represent in your programs—anything from a checking account to an alien spacecraft—are real-life objects. OOP lets you represent these real-life objects as software objects. Like real-life objects, software objects combine characteristics (called attributes in OOP-speak) and behaviors (called methods in OOP-speak). For example, if you were to create an alien spacecraft object, its attributes could include its location and energy level, while its methods could include its ability to move or fire its weapons.
Objects are created (or instantiated in OOP-speak) from a definition called a class—programming code that can define attributes and methods. Classes are like blue-prints. A class isn't an object, it's a design for one. And just as a foreman can create many houses from the same blueprint, a programmer can create many objects from the same class. As a result, each object (also called an instance) instantiated from the same class will have a similar structure. So, if you have a checking account class, you could use it to create multiple checking account objects. And those different objects would each have the same basic structure. Each might have a balance attribute, for example.
But just as you can take two houses built from the same blueprint and decorate them differently, you can have two objects of the same class and give each its own, unique set of attribute values. So, you could have one checking account object with a balance attribute of 100 and another with a balance attribute of 1,000,000.
HINT | Don't worry if all this OOP talk isn't crystal clear yet. I just wanted to give you an overview of what objects are all about. Like all new programming concepts, reading about them isn't enough. But after seeing some real Python code that defines classes and creates objects (and coding some on your own), you'll soon "get" OOP. |
Категории