Object oriented programming combines elements of variable and functions into objects. Each object can store data like a variable, but unlike a variable, object can call methods which can change or return information like a function. The data that an object is stored is called that particular object's state. Each object is a particular instance of a class. A class describes the general properties of objects in the class, and the general methods, but does not describe the state for any particular instance. Let's make this a bit more concrete. Let's think about the class of people we know as Students. Students in general have some properties that describe their state. What might some of these properties be? Students also might perform certain actions. What might some of these actions be? A Student object is a particular student you might have in mind. That student has specific values for the general properties described by the Student class.
>>> s="hello" >>> s.upper() 'HELLO'In this context, upper is a method in the string class and can operate on any string object. If you would like to know which methods are available in the string class, run help(str) in the python shell. The general syntax for calling a method on a object is
<object name>.<method name>(<parameters>)In the string class, upper, lower, title, isupper, islower, isalpha, split,join, and strip are all methods you are likely to use at least once this semester. Ideally, from this point on, you should not need to use from string import * anymore and can instead use built in string methods.
Lists are the other type of built-in data type that are actually part of a class. If you type help(list) in the python shell, you will get a list of list methods. Ignore the ones beginning with underscores __. Take a look at append and reverse. We'll talk about others as needed.
>>> l=range(5) >>> l=range(5) >>> l [0, 1, 2, 3, 4] >>> l.append(7) >>> l [0, 1, 2, 3, 4, 7] >>> silly = l.append(8) >>> print silly None >>> print l [0, 1, 2, 3, 4, 7, 8] >>> l.reverse() >>> l [8, 7, 4, 3, 2, 1, 0] >>>What does append return? What does append do? The answers to these questions are a common source of confusion for beginners (and even sometimes experts.)
>>> import graphics >>> help(graphics) >>> from graphics import *We also have posted a Graphics Quick Reference online. Objects are created by calling a constructor. The constructor has the same name as a class and is responsible for creating specific instance of a class (an object). Let's create a graphics window and add some objects.
>>> win=GraphWin("hello", 200, 200) >>> center = Point(100,100) >>> center.draw(win) >>> circ1 = Circle(center, 50) >>> circ1.draw(win) >>> circ1.setFill("red")Try creating some more objects and trying out their methods.