Introduction to Object Oriented Programming.pdf
Document Details
Uploaded by AvidMoonstone
Full Transcript
Python OOP Introduction to Object Oriented Programming Learning Outcomes After going through this module, you will be able to: Understand the importance of Object-Oriented Programming Understand the basic principles of Object-Oriented Design Identify objects...
Python OOP Introduction to Object Oriented Programming Learning Outcomes After going through this module, you will be able to: Understand the importance of Object-Oriented Programming Understand the basic principles of Object-Oriented Design Identify objects, attribute, and methods Create a simple UML diagram Transform UML diagram to a Class in Python Programming Paradigm: A programming paradigm is a fundamental style or approach to computer programming that defines how tasks are structured, organized, and accomplished within a given programming language or environment. It encompasses a set of principles, concepts, and practices that guide the design and implementation of software systems. Different 1 programming paradigms emphasize various concepts, such as data flow, control flow, and the organization of code, leading to distinct programming styles and methodologies. Different types of Programming Paradigm. Procedural Programming Procedural Programming can also be referred to as imperative programming. It is a programming paradigm based upon the concept of procedure calls, in which statements are structured into procedures (also known as subroutines or functions). They are a list of instructions to tell the computer what to do step by step, Procedural programming languages are known as top-down languages. Most of the early programming languages are all procedural. Examples of Fortran C and Cobol. Here is a sample code in COBOL. IDENTIFICATION DIVISION. PROGRAM-ID. HELLO. PROCEDURE DIVISION. DISPLAY ‘Hello World!’. STOP RUN. Features of Procedural Code Procedural Programming is excellent for general-purpose programming The coded simplicity along with ease of implementation of compilers and interpreters The source code is portable The code can be reused in different parts of the program, without the need to copy it The program flow can be tracked easily as it has a top-down approach. Here's a simple example that calculates the sum of numbers from 1 to N procedurally: def calculate_sum(n): total = 0 for i in range(1, n + 1): total += i return total n = 5 result = calculate_sum(n) print(f"The sum of numbers from 1 to {n} is {result}."). Logical Programming Logical programming is a paradigm that has its foundations in mathematical logic in which program statements express facts and rules about problems within a system. Rules are written as logical clauses with a head and a body. They also follow a declarative rather than an imperative approach. To understand how a problem can be solved in logical programming, you need to know about the building blocks − Facts and Rules − Let us understand the difference between Imperative and declarative programming. Imagine you walk into your favorite coffee place and you would like to order some coffee. The imperative approach will be: Enter the coffee shop Queue in the line and wait for the barista asking you for your order Order Yes, for takeaway, please Pay Present your loyalty card to collect points Take your order and walk away The declarative approach: A large latte for takeaway, please So rather than providing a step by step instruction (imperative), you tell the system what you need and let it try to come up with a solution (declarative). Prolog follows the Logical paradigm and is probably the most famous language in the logical programming family. Prolog has been enormously influential in the domains of theorem proving, expert systems, natural language processing and in the field of artificial intelligence (notably IBM’s Watson2) in general. Prolog, like SQL, has two main aspects, one to express the data and another to query it. The basic constructs of logical programming, terms, and statements, are inherited from logic. Features of Logical Programming Logical programming can be used to express knowledge in a way that does not depend on the implementation, making programs more flexible, compressed and understandable. It enables knowledge to be separated from use, i.e. the machine architecture can be changed without changing programs or their underlying code. It can be altered and extended in natural ways to support special forms of knowledge, such as meta-level of higher-order knowledge. It can be used in non-computational disciplines relying on reasoning and precise means of expression. Here's an example in Prolog syntax that defines a rule to check if a person is a parent: parent(john, mary). parent(john, jim). parent(susan, mary). parent(susan, jim). is_parent(X, Y) :- parent(X, Y). This code defines parent-child relationships and a rule is_parent(X, Y) that checks if X is a parent of Y.. Functional Programming Functional programming is a programming paradigm where you have a style of building the structure and elements of computer programs. Here you treat computation as an evaluation of mathematical functions and you avoid changing-state and mutable data. Functional programming consists only of PURE functions. Pure functions are those which take an argument list as an input and whose output is a return value. Now you may feel that all functions are pure as any function takes in values and returns a value. For example, if a function relies on the global variable or class member’s data, then it is not pure. And in such cases, the return value of that function is not entirely dependent on the list of arguments received as input and can also have side effects. So, what do you understand by the term side effect? A side effect is a change in the state of an application that is observable outside the called function other than its return value. Features of Functional Paradigm Pure functions – In case of pure functions, the output depends only on the input. Recursion-A recursive function is a function that calls itself during its execution. This enables the function to repeat itself several times, the result being outputted at the end of each iteration. Below is an example of a recursive function. Referential transparency-An expression is said to be referentially transparent if it can be replaced with its corresponding value without changing the program's behavior. As a result, evaluating a referentially transparent function gives the same value for fixed arguments. Functions are First-Class and can be Higher-Order-A programming language is said to have First-class functions when functions in that language are treated like any other variable. For example, in such a language, a function can be passed as an argument to other functions, can be returned by another function and can be assigned as a value to a variable. Higher-order functions are functions that take at least one first-class function as a parameter. Variables are Immutable-In functional programming you cannot modify a variable after it has been initialized. You can create new variables and this helps to maintain state throughout the runtime of a program. def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1) n = 5 result = factorial(n) print(f"The factorial of {n} is {result}."). Object-Oriented Programming(OO): In this framework, all real-world entities are represented by Classes. Objects are instances of classes so each object encapsulates a state and behavior. State implies the fields, attributes of the object and behavior is what you do with the state of the object and they are the methods. Objects interact with each other by passing messages. Features of Object-Oriented: Encapsulation – This is a fundamental feature of Object-Oriented Programming. Here you hide unnecessary details in classes and deliver a simple and clear interface for working. It describes the idea of bundling data and methods that work on that data within one unit. This concept is also often used to hide the internal representation, or state, of an object from the outside Inheritance - Inheritance is one of the core concepts of object- oriented programming (OOP) languages. It is a mechanism where you can derive a class from another class for a hierarchy of classes that share a set of attributes and methods. It explains how the class hierarchies develop code readability and support to the reuse of functionality. Data Abstraction - to Data abstraction is the reduction of a particular body of data to a simplified representation of the whole. Data abstraction is usually the first step in database design. Polymorphism - Polymorphism is an object-oriented programming concept that refers to the ability of a variable, function or object to take on multiple forms. Programming languages that have implemented the OO paradigm are: Ruby, Java, C++, Python, Simula(the first OOP language) Here's a Python code snippet that demonstrates the Object-Oriented Programming (OOP) approach. class Person: def __init__(self, name, age): self.name = name self.age = age def introduce(self): return f"Hi, I'm {self.name} and I'm {self.age} years old." # Creating instances (objects) of the Person class person1 = Person("Alice", 30) person2 = Person("Bob", 25) # Calling methods on objects print(person1.introduce()) print(person2.introduce()) Benefits of OOP Approach The Object-Oriented Programming (OOP) approach offers several benefits in software development, making it a widely used and favored paradigm. Here are some of the key advantages of using OOP: Modularity: OOP promotes the modular design of software. You can break down complex systems into smaller, manageable objects and classes. Each object encapsulates its data and behavior, making it easier to understand and maintain. Reusability: OOP encourages code reusability. You can create classes that can be used as templates for creating multiple instances of objects. This reduces duplication of code and saves development time. Encapsulation: OOP allows you to encapsulate data and behavior within an object. This means that an object's internal state is hidden from the outside world, and interactions with the object are controlled through well-defined interfaces. This enhances data security and reduces unintended interference. Abstraction: Abstraction is a core concept in OOP. It allows you to model real-world entities and concepts in a simplified manner. You can create abstract classes and methods that define common attributes and behaviors, and then derive concrete classes from them. Inheritance: Inheritance enables you to create new classes (derived or child classes) based on existing classes (base or parent classes). This promotes code reuse and allows you to extend and specialize the behavior of existing classes. Polymorphism: Polymorphism allows objects of different classes to be treated as objects of a common superclass. This enables flexibility in designing systems and supports dynamic method dispatch, making it easier to work with different types of objects in a unified way. Organization and Maintainability: OOP provides a natural way to organize code. Objects represent real-world entities, which makes it easier for developers to relate the code to the problem domain. Well- organized code is easier to maintain and update over time. Collaboration: OOP promotes collaboration among developers. Multiple developers can work on different classes and objects simultaneously, as long as they adhere to the defined interfaces. This encourages teamwork and parallel development. Modeling Real-World Scenarios: OOP aligns well with modeling real- world scenarios and entities. It allows you to create software that mirrors the structure and behavior of objects and concepts in the problem domain. Testing and Debugging: OOP can simplify testing and debugging. Since objects encapsulate their behavior, you can test them in isolation, which promotes unit testing. Additionally, clear interfaces and well-defined behaviors make it easier to identify and fix issues. Code Extensibility: OOP supports code extensibility. You can add new classes and objects to extend the functionality of a system without modifying existing code. This follows the Open-Closed Principle from SOLID design principles. Adaptability and Scalability: OOP allows systems to be adaptable and scalable. You can add new classes to accommodate changing requirements, and you can scale systems by creating more instances of objects as needed. Introducing object-oriented An object is a tangible thing that we can sense, feel, and manipulate. As kids we interact with objects such as baby toys. Even at young age we can quickly learn that these objects can do certain things like bells ring, buttons are pressed, and levers are pulled. For example, a toy robot, what are the data we can get from it. What are the things that they can do? What are the things that we can do to it? Source: https://unsplash.com/photos/Ejcuhcdfwrs Toy Robot data: name, color behaviors: turn on, turn off, say Software objects may not be tangible things that you can pick up, sense, or feel, but they are models of something that can do certain things and have certain things done to them. Formally, an object is a collection of data and associated behaviors. Object-oriented programming means writing code directed toward modeling objects. It is defined by describing a collection of interacting objects via their data and behavior. Object-oriented analysis (OOA) is the process of looking at a problem, system, or task (that somebody wants to turn into a working software application) and identifying the objects and interactions between those objects. The analysis stage is all about what needs to be done. Output of analysis stage – Description of the system (requirements) – Requirements into a task Object-oriented design (OOD) is the stage of transforming what should be done into how it should be done. It is a process of converting the requirements from OOA into an implementation specification. In this stage we should name the objects, identify its behavior, and specify which objects affects other objects. Output – Implementation specification Object-oriented programming (OOP) is the process of converting a design into a working program that does what the product owner originally requested. Objects and classes An object is a collection of data with associated behaviors. Let’s take the world of Power Rangers for example. Each individual Ranger is like an object. They have their own unique characteristics (name, color, skills) and abilities (fighting, using weapons). These Rangers are instance of a common class, which defines what a Power Ranger is and what abilities they all share. Source: https://media.comicbook.com/2015/12/ powerrangersheader-163509.jpg Class: Power Ranger Attributes: Name (string), Color (string), Special Ability (String), Weapon (string) Methods: Fight(), UseSpecialAbility(), UseWeapon() Each Power Ranger (object) is an instance of the Power Ranger class. For example, there could be a “Red Ranger” object and a “Blue Ranger” object, each with their own unique attributes and abilities. To demonstrate association between classes, we can add a class called “Zord” that represents the giant robotic vehicles the Power Rangers use to fight larger enemies. Word are closely associated with Power Ranges and play a significant role in their battles. Class: Zord Attributes: Type (string), Color (string), Weapon (string) Methods: Transform(), Attack() Unified Modeling Language (UML) Diagram UML diagrams are a vital tool in software engineering for improving communication, analysis, design, and documentation of software systems. They facilitate collaboration among team members and enhance the overall quality of software projects by providing a clear and standardized way to represent and understand complex systems. Creating basic UML (Unified Modeling Language) diagrams involves using standard UML notation to represent various aspects of a software system, including classes, relationships, attributes, methods, and more. Here's a brief overview of the basic syntax for creating UML diagrams: 1. Class Diagrams Class diagrams are used to represent the structure and relationships between classes in a system. The basic syntax for a class in a class diagram is as follows: +---------------------+ | Class Name | +---------------------+ | - Attribute1: Type | | - Attribute2: Type | +---------------------+ | + Method1() | | + Method2() | +---------------------+ + denotes a public member (method or attribute). - denotes a private member. # denotes a protected member. ~ denotes a package-level member (not commonly used). 2. Relationships Relationships between classes are represented using lines connecting the classes. Common relationship types include: Association (a simple connection between classes). Aggregation (a "whole-part" relationship). Composition (a stronger form of aggregation). Inheritance (for representing class inheritance). Dependency (a weaker relationship, often used for method dependencies). Here's a basic example of an association relationship: +-------------+ +-------------+ | Class A | | Class B | +-------------+ +-------------+ | | | | | | | | | +----->| | | | | | | | | | +-------------+ +-------------+ 3. Attributes and Methods Attributes (class properties) are listed with their names and data types. Methods (class behaviors) are listed with their names and parameters. 4. Multiplicity In class diagrams, you can specify the multiplicity of associations to indicate how many instances of one class are related to instances of another class. For example: 0..1: Zero or one instance. 1: Exactly one instance. 0..* or *: Zero or more instances. 1..*: One or more instances. Here's an example of multiplicity notation: +-------------+ +-------------+ | Class A | | Class B | +-------------+ +-------------+ | | | | | | | | | +----->| | | | | | | | | | +-------------+ +-------------+ 1..* 0..1 5. Inheritance Inheritance relationships in UML are represented with a solid line with an arrowhead pointing to the superclass (base class). The arrowhead is often labeled with the keyword "extends." +-----------------+ +-----------------+ | Superclass | | Subclass | +-----------------+ +-----------------+ | | | | | | | | | +---> | | | | | | | | | | +-----------------+ +-----------------+ UML Diagram of Power Ranger and Zord Classes and their relationship +-----------------------------------+ | PowerRanger | +-----------------------------------+ | - name: string | | - color: string | | - zord: Zord | +-----------------------------------+ | + PowerRanger(name: string, | | color: string) | | + AssignZord(assignedZord: Zord) | | + FightEnemy() | +-----------------------------------+ | | | 1 | | v +-----------------------------------+ | Zord | +-----------------------------------+ | - type: string | | - color: string | | - weapon: string | +-----------------------------------+ | + Zord(type: string, | | color: string, weapon: string)| | + Transform() | | + Attack() | +-----------------------------------+ In this UML diagram: The association between the PowerRanger and Zord classes is represented by a solid line connecting the PowerRanger class to the Zord class. The number 1 near the end of the association line indicates that a PowerRanger object can be associated with one Zord object. This is a one-to-one relationship. The diamond-shaped arrowhead at the PowerRanger end of the line indicates that PowerRanger is the owner or "navigates" the relationship, meaning it has a reference to a Zord object. There is no arrowhead at the Zord end of the line, indicating that Zord objects do not necessarily have a reference to PowerRanger objects. Defining Class in Python Here is the basic outline of how to create a class: class ClassName: def __init__(self, attribute1, attribute2): self.attribute1 = attribute1 self.attribute2 = attribute2 def method1(self, parameter1): # Method code here pass def method2(self, parameter2): # Method code here pass class ClassName: This is the keyword ‘class’ followed by the name you choose for your class (e.g., PowerRanger or Zord). def __init__(self, attribute1, attribute2): This is the constructor method (also called __init__). It's responsible for initializing the attributes of the object. self is a reference to the instance of the class being created. You can define any number of attributes here. self.attribute1 = attribute1: This line assigns the value of attribute1 (passed as an argument) to the object's attribute1. def method1(self, parameter1): This is an example of a method. Methods take self as the first parameter (required), which refers to the instance of the class. Additional parameters can be added just like regular function parameters. class Zord: def __init__(self, zord_type: str, color: str, weapon: str): self.type = zord_type self.color = color self.weapon = weapon def transform(self): print(f"{self.color} {self.type} Zord is transforming!") def attack(self): print(f"{self.color} {self.type} Zord is attacking with {self.weapon}!") class PowerRanger: def __init__(self, name: str, color: str): self.name = name self.color = color self.zord = None # The Power Ranger's associated Zord def assign_zord(self, zord: Zord): self.zord = zord print(f"{self.name} is now associated with a {zord.color} {zord.type} Zord!") def fight_enemy(self): if self.zord: print(f"{self.color} {self.name} Ranger and their {self.zord.color} {self.zord.type} Zord are ready to fight!") self.zord.transform() self.zord.attack() else: print(f"{self.color} {self.name} Ranger needs a Zord to fight!") # Creating Zords red_zord = Zord(zord_type="T-Rex", color="Red", weapon="Dino Sword") blue_zord = Zord(zord_type="Triceratops", color="Blue", weapon="Tricera Shield") # Creating Power Rangers red_ranger = PowerRanger(name="Jason", color="Red") blue_ranger = PowerRanger(name="Billy", color="Blue") # Associating Power Rangers with Zords red_ranger.assign_zord(red_zord) blue_ranger.assign_zord(blue_zord) # Power Rangers in action red_ranger.fight_enemy() blue_ranger.fight_enemy() Output: Jason is now associated with a Red T-Rex Zord! Billy is now associated with a Blue Triceratops Zord! Red Jason Ranger and their Red T-Rex Zord are ready to fight! Red T-Rex Zord is transforming! Red T-Rex Zord is attacking with Dino Sword! Blue Billy Ranger and their Blue Triceratops Zord are ready to fight! Blue Triceratops Zord is transforming! Blue Triceratops Zord is attacking with Tricera Shield! To enhance the quality of your code, follow the tips below: Use type hint in parameters and methods. Follow Python’s style guide, use PEP 8. Use underscores for methods and attribute names and using CapitalizedWords for class names (e.g. MyClass). Provide clear documentation for your classes, methods, and attributes using Docstrings. Name methods using verbs that describe the action they perform. Defining Class in C# class ClassName { // Fields (attributes) private int attribute1; private string attribute2; // Constructor public ClassName(int attribute1, string attribute2) { this.attribute1 = attribute1; this.attribute2 = attribute2; } // Method 1 public void Method1(int parameter1) { // Method code here } // Method 2 public void Method2(string parameter2) { // Method code here } } In this C# code: We define a class called ClassName. The class has two private fields: attribute1 of type int and attribute2 of type string. We provide a constructor that initializes these fields when an object of the class is created. There are two methods, Method1 and Method2, which correspond to the Python methods method1 and method2. You can add the respective code for these methods as needed. Here’s the equivalent C# code for the provided Python classes Zord and PowerRanger: using System; class Zord { // Fields (attributes) private string type; private string color; private string weapon; // Constructor public Zord(string zordType, string zordColor, string zordWeapon) { type = zordType; color = zordColor; weapon = zordWeapon; } // Transform method public void Transform() { Console.WriteLine($"{color} {type} Zord is transforming!"); } // Attack method public void Attack() { Console.WriteLine($"{color} {type} Zord is attacking with {weapon}!"); } } class PowerRanger { // Fields (attributes) private string name; private string color; private Zord zord; // The Power Ranger's associated Zord // Constructor public PowerRanger(string rangerName, string rangerColor) { name = rangerName; color = rangerColor; zord = null; // The Power Ranger starts without an associated Zord } // AssignZord method public void AssignZord(Zord assignedZord) { zord = assignedZord; Console.WriteLine($"{name} is now associated with a {zord.color} {zord.type} Zord!"); } // FightEnemy method public void FightEnemy() { if (zord != null) { Console.WriteLine($"{color} {name} Ranger and their {zord.color} {zord.type} Zord are ready to fight!"); zord.Transform(); zord.Attack(); } else { Console.WriteLine($"{color} {name} Ranger needs a Zord to fight!"); } } } In this C# code: We define the Zord class with a constructor, Transform method, and Attack method to replicate the behavior of the Python Zord class. We define the PowerRanger class with a constructor, AssignZord method, and FightEnemy method to replicate the behavior of the Python PowerRanger class. Here's the equivalent C# code for the provided Python code that creates Zords, Power Rangers, associates Power Rangers with Zords, and demonstrates their actions: class Program { static void Main(string[] args) { // Creating Zords Zord redZord = new Zord(zordType: "T-Rex", zordColor: "Red", zordWeapon: "Dino Sword"); Zord blueZord = new Zord(zordType: "Triceratops", zordColor: "Blue", zordWeapon: "Tricera Shield"); // Creating Power Rangers PowerRanger redRanger = new PowerRanger(rangerName: "Jason", rangerColor: "Red"); PowerRanger blueRanger = new PowerRanger(rangerName: "Billy", rangerColor: "Blue"); // Associating Power Rangers with Zords redRanger.AssignZord(redZord); blueRanger.AssignZord(blueZord); // Power Rangers in action redRanger.FightEnemy(); blueRanger.FightEnemy(); } } Practice Sets: Write down the identified objects, their data (attributes), and their behavior (methods). Try to come up with at least three attributes and two methods for each object. Draw a class diagram for each object. Create a class definition in Python for each object.. Household appliances like a washing machine, microwave oven, and vacuum cleaner.. Animals like cat, dog, and bird.. Products in online shopping system.