首页 > 代码库 > Object-oriented features

Object-oriented features

Python is an object-oriented programing language, which means that it provides features that support object-oriented programming. It is easy to define object-oriented programming, but we have already seen some of its characteristics:

  • Programs are made up of object definitions and function definitions, and most of the computation is expressed in terms of operations on objects.
  • Each object definition corresponds to some object or concept in the real world, and the functions that operate on that object correspond to the ways real-world objects interact.

For example, the Time class defined to the way people record the time of day, and the functions we defined correspond to the kinds of things people do with times. Similarly, the Point and Rectangle classes correspond to the mathematical concepts of a point and a rectangle.

So far, we have not taken advantage of the features Python provides to support object-oriented programming. Strictly speaking, these features are not necessary. For the most part, they provide an alternative syntax for things we have already done, but in many cases, the alternative is more concise and more accurately conveys the structure of the program.

For example, in the Time program, there is no obvious connection between the class definition and the function definitions that follow. With some examination, it is apparent that every function takes at least one Time object as an argument. This observation is the motivation for methods; a method is a function that is associated with a particular class. For example, we have seen methods for strings, lists, dictionaries and tuples. We will define methods for user-defined types.

Methods are semantically the same as functions, but there are two syntactic differences:

  • Methods are defined inside a class definition in order to make the relationship between the class and the method explicit.
  • The syntax for invoking a method is different from the syntax for calling a function.

Example:

class Time:    """ represents the time of day        attributes: hour, minute, second        method: print_time, increment, int_to_time                time_to_int, after """    def print_time(self):        print(%.2d:%.2d:%.2d % (self.hour,self.minute,self.second))    @staticmethod    def int_to_time(seconds):        time = Time()        minute,time.second = divmod(seconds,60)        time.hour,time.minute = divmod(minute,60)        return time    def time_to_int(self):        return self.second + self.minute*60 + self.hour*3600    def increment(self,t):        t1 = self.time_to_int()        t2 = t.time_to_int()        time = Time()        time = Time.int_to_time(t1+t2)        return time    def after(self,t):        return self.time_to_int() > t.time_to_int()time = Time()time.hour = 9time.minute = 4time.second = 0

from Thinking in Python

 

Object-oriented features