Python is an object-oriented programming language. Object-oriented programming (OOP) is a programming paradigm based on the concept of “objects”, which can contain data (attributes) and code (methods). The following are four important object-oriented characteristics possessed by Python:
1. Class and Method Definitions
Python allows defining custom types using classes. A class is a blueprint for creating objects. It can contain attributes (data) and methods (functions). Methods define the behavior of the class. For example, in the Time
class, methods like print_time()
and increment()
are defined to operate on time objects.
Example:
class Time: def print_time(self): print('%.2d:%.2d:%.2d' % (self.hour, self.minute, self.second))
This structure clearly defines what the object represents and how it behaves.
2. Computation is Expressed in Terms of Objects
In object-oriented programming, most of the operations are performed by invoking methods on objects. Objects are the primary agents of computation.
Example:
start = Time() start.hour = 9 start.minute = 45 start.second = 0 start.print_time()
Here, instead of calling a function and passing the object, the method print_time()
is invoked directly on the object start
. This shows that the computation is happening through the object.
3. Real-world Modeling
Objects in Python often represent entities in the real world, and the methods represent actions associated with those entities. For instance, the Time
class is used to model the time of day. This makes the code easier to understand and relate to real-world problems.
Example:
duration = Time(1, 35) end = start + duration
This represents adding the duration of an event to a starting time, just as it would be done in the real world.
4. Method-Object Relationship
In Python, methods are defined within a class and are closely tied to the object on which they operate. The first parameter of a method is always self
, which refers to the instance calling the method. This relationship makes it easy to manage state and behavior together.
Example:
class Time: def increment(self, seconds): seconds += self.time_to_int() return int_to_time(seconds)
Here, self
refers to the instance of the Time
class, and the method increment()
modifies or returns data relevant to that particular instance.
These four characteristics—class and method definitions, computation via objects, real-world modeling, and the close relationship between methods and objects—form the foundation of object-oriented programming in Python. They help in writing modular, reusable, and organized code.