Treat Objects as Objects

Learn about the practical aspects of identifying objects, wrapping data behaviors, and considering class-based data encapsulation.

In previous chapters, we’ve covered many of the defining features of object-oriented programming. We now know some principles and paradigms of object-oriented design, and we’ve covered the syntax of object-oriented programming in Python.

Yet, we don’t know exactly how and, especially, when to utilize these principles and syntax in practice. In this chapter, we’ll discuss some useful applications of the knowledge we’ve gained, looking at some new topics along the way:

  • How to recognize objects
  • Data and behaviors, once again
  • Wrapping data behaviors using properties
  • The Don’t Repeat Yourself principle and avoiding repetition

In this chapter, we’ll also address some alternative designs for our case study problem. We’ll look at ways to partition the sample data into training sets and test sets.

We’ll start this chapter with a close look at the nature of objects and their internal state. There are cases when there’s no state change, and a class definition isn’t desirable.

Identify objects

Identifying objects is a very important task in object-oriented analysis and programming. But it isn’t always as easy as counting the nouns in short paragraphs that, frankly, the authors have constructed explicitly for that purpose. Remember, objects are things that have both data and behavior. If we are working only with data, we are often better off storing it in a list, set, dictionary, or other Python data structure. On the other hand, if we are working only with behavior, but no stored data, a simple function is more suitable.

An object, however, has both data and behavior. Proficient Python programmers use built-in data structures unless (or until) there is an obvious need to define a class. There is no reason to add an extra level of complexity if it doesn’t help organize our code. On the other hand, the need is not always self-evident.

Wrap data in the class

We can often start our Python programs by storing data in a few variables. As the program expands, we will later find that we are passing the same set of related variables to a set of functions. This is the time to think about grouping both variables and functions into a class.

Example

For example, if we are designing a program to model polygons in two-dimensional space, we might start with each polygon represented as a list of points.

Get hands-on with 1400+ tech skills courses.