Thinking About Classes and InstancesΒΆ

You can now imagine some reasons you may want to define a class. You have seen examples of creating types that are more complicated or specific than the ones built in to Python (like lists or strings). Turtle, with all the instance variables and methods you learned about using earlier in the semester, is a class that programmers defined which is now included in the Python language. In this chapter, we defined Point with some functionality that can make it easier to write programs that involve x,y coordinate Point instances. And shortly, you’ll see how you can define classes to represent objects in a game.

You can also use self-defined classes to hold data – for example, data you get from making a request to a REST API.

Before you decide to define a new class, there are a few things to keep in mind, and questions you should ask yourself:

After considering those questions and making decisions about how you’re going to get start with a class definition, you can begin to define your class.

Remember that a class definition, like a function definition, is a general description of what every instance of the class should have. (Every Point has an x and a y.) The class instances are specific: e.g. the Point with a specific x and y >. You might have a Point with an x value of 3 and a y value of 2, so for that particular instance of the class Point, you’d pass in 3 and 2 to the constructor, the __init__ method, like so: new_point = Point(3,2), as you saw in the last sections.

Next Section - Defining Classes with Data from the Internet