/
ict
/
techshare_sites
Обзор
Документация
Войти
/
ict
/
techshare_sites
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
Object-Oriented-Programming-in-Python.html
1 689 строк
87 KB
root
Spinning wheel
19 ноя 2025, 13:13
19 ноя 2025, 13:13
01ebf54
Код
Авторство
О чём код?
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Object-Oriented Programming in Python</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; } body { background: linear-gradient(135deg, #1a2a6c, #b21f1f, #fdbb2d); color: #333; line-height: 1.6; overflow-x: hidden; } .container { max-width: 1200px; margin: 0 auto; padding: 20px; } header { text-align: center; padding: 40px 20px; background: rgba(255, 255, 255, 0.9); border-radius: 10px; box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2); margin-bottom: 30px; } h1 { font-size: 2.8rem; margin-bottom: 15px; color: #1a2a6c; } .subtitle { font-size: 1.4rem; color: #555; margin-bottom: 20px; } .quote { font-style: italic; font-size: 1.2rem; color: #777; margin: 20px 0; padding: 15px; border-left: 4px solid #fdbb2d; background: rgba(253, 187, 45, 0.1); } .section { background: rgba(255, 255, 255, 0.9); border-radius: 10px; padding: 30px; margin-bottom: 30px; box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1); transition: transform 0.3s ease; } .section:hover { transform: translateY(-5px); } h2 { color: #1a2a6c; margin-bottom: 20px; padding-bottom: 10px; border-bottom: 2px solid #fdbb2d; } h3 { color: #b21f1f; margin: 20px 0 10px; } p { margin-bottom: 15px; } .analogy { background: rgba(26, 42, 108, 0.1); padding: 20px; border-radius: 8px; margin: 20px 0; } .analogy h4 { color: #1a2a6c; margin-bottom: 10px; } .code-block { background: #2d2d2d; color: #f8f8f2; padding: 20px; border-radius: 8px; margin: 20px 0; overflow-x: auto; font-family: 'Courier New', monospace; line-height: 1.4; } .code-comment { color: #75715e; } .code-keyword { color: #f92672; } .code-function { color: #66d9ef; } .code-string { color: #e6db74; } .code-var { color: #a6e22e; } .interactive-demo { background: #f5f5f5; padding: 20px; border-radius: 8px; margin: 20px 0; } .demo-controls { display: flex; gap: 10px; margin-bottom: 15px; flex-wrap: wrap; } button { background: #1a2a6c; color: white; border: none; padding: 10px 15px; border-radius: 5px; cursor: pointer; transition: background 0.3s; } button:hover { background: #b21f1f; } .output { background: white; padding: 15px; border-radius: 5px; border: 1px solid #ddd; min-height: 100px; font-family: 'Courier New', monospace; } .pillars { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px; margin: 20px 0; } .pillar { background: white; padding: 20px; border-radius: 8px; box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1); text-align: center; transition: transform 0.3s; } .pillar:hover { transform: translateY(-5px); } .pillar h4 { color: #1a2a6c; margin-bottom: 10px; } .comparison { display: flex; flex-wrap: wrap; gap: 20px; margin: 20px 0; } .comparison-item { flex: 1; min-width: 300px; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1); } /* Added styling for images */ .presentation-image { max-width: 100%; border-radius: 8px; margin: 20px 0; box-shadow: 0 3px 10px rgba(0, 0, 0, 0.2); } /* Added styles for interactive exercises */ .exercise-container { background-color: #f0f8ff; border: 2px solid #4682b4; border-radius: 8px; padding: 20px; margin: 20px 0; } .exercise-header { font-weight: bold; color: #1a2a6c; margin-bottom: 10px; } .exercise-description { margin-bottom: 15px; } .code-editor { width: 100%; min-height: 150px; font-family: 'Courier New', monospace; padding: 10px; border: 1px solid #ccc; border-radius: 4px; resize: vertical; background-color: #fff; } .exercise-buttons { margin-top: 10px; } .exercise-btn { background: #4682b4; color: white; border: none; padding: 8px 15px; border-radius: 4px; cursor: pointer; margin-right: 10px; } .exercise-btn:hover { background: #5a9dd6; } .exercise-output { margin-top: 15px; padding: 10px; border-radius: 4px; background-color: #2d2d2d; color: #f8f8f2; font-family: 'Courier New', monospace; min-height: 50px; white-space: pre-wrap; } .success-message { color: #7fff00; } .error-message { color: #f92672; } footer { text-align: center; padding: 20px; color: white; margin-top: 30px; } @media (max-width: 768px) { h1 { font-size: 2.2rem; } .subtitle { font-size: 1.2rem; } .section { padding: 20px; } } </style> </head> <body> <div class="container"> <header> <h1>Object-Oriented Programming in Python</h1> <p class="subtitle">Explained in Plain English</p> <!-- Removed Einstein quote --> <p>An interactive guide to understanding OOP concepts with Python examples</p> </header> <section class="section"> <h2>What is OOP?</h2> <p>Object-oriented programming is a popular way to write computer programs that organizes code around objects rather than actions.</p> <img src="assets/image/OOP_Images/Image1.png" alt="Introduction to OOP" class="presentation-image"> <div class="analogy"> <h4>The House Building Analogy</h4> <p>Imagine you run a construction company building 100 houses. Instead of designing each house from scratch, you use the same blueprint for all houses.</p> <ul> <li><strong>Blueprint</strong> = Class</li> <li><strong>House</strong> = Instance of a class or object</li> <li><strong>House-oriented building</strong> = Object-oriented programming</li> </ul> </div> <p>Just as house-oriented building is efficient for constructing homes, OOP is efficient for writing computer programs.</p> </section> <section class="section"> <h2>The Four Pillars of OOP</h2> <img src="assets/image/OOP_Images/Image2.png" alt="Four Pillars of OOP" class="presentation-image"> <div class="pillars"> <div class="pillar"> <h4>Polymorphism</h4> <p>Ability of an object to take many forms</p> <p><em>Example: A house can have different types of roofs, windows, doors</em></p> </div> <div class="pillar"> <h4>Inheritance</h4> <p>Child classes acquire properties from parent classes</p> <p><em>Example: A house gaining a new feature like a garage</em></p> </div> <div class="pillar"> <h4>Encapsulation</h4> <p>Protects data and methods from outside misuse</p> <p><em>Example: Keeping kids out of the garage with a key</em></p> </div> <div class="pillar"> <h4>Abstraction</h4> <p>Hides unnecessary details from the user</p> <p><em>Example: Considering the final house, not construction materials</em></p> </div> </div> </section> <section class="section"> <h2>Classes and Instances</h2> <p>A class is a blueprint that defines how an instance (object) will look and behave.</p> <img src="assets/image/OOP_Images/Image3.png" alt="Classes and Instances" class="presentation-image"> <h3>Creating Classes Manually</h3> <div class="code-block"> <span class="code-keyword">class</span> <span class="code-function">house</span>():<br> <span class="code-keyword">pass</span><br> <br> house1 = house()<br> house2 = house()<br> <br> house1.address = 1234<br> house1.state = <span class="code-string">"california"</span><br> house1.Alarm = <span class="code-keyword">False</span><br> house1.price = 300000<br> <br> house2.address = 5678<br> house2.state = <span class="code-string">"texas"</span><br> house2.Alarm = <span class="code-keyword">True</span><br> house2.price = 100000<br> <br> <span class="code-function">print</span>(house1.state)<br> <span class="code-function">print</span>(house2.price)<br> <br> <span class="code-comment"># Output:</span><br> <span class="code-comment"># california</span><br> <span class="code-comment"># 100000</span> </div> <p>This approach works but is inefficient for creating many objects. Let's improve it with <code>__init__</code>.</p> <div class="exercise-container"> <div class="exercise-header">Exercise 1: Creating a Simple Class</div> <div class="exercise-description"> Create a class called "Car" with attributes: brand, model, and year. Then create an instance of this class. </div> <textarea class="code-editor" id="exercise1-editor"># Write your code here # 1. Create a Car class with __init__ method # 2. Add brand, model, and year parameters # 3. Create an instance of your Car class # 4. Print the car's details class Car: pass # Replace this with your implementation # Create an instance here</textarea> <div class="exercise-buttons"> <button class="exercise-btn" onclick="checkExercise1()">Check Answer</button> <button class="exercise-btn" onclick="resetExercise1()">Reset</button> <button class="exercise-btn" onclick="showSolution1()">Show Solution</button> </div> <div class="exercise-output" id="exercise1-output">Run your code to see output here...</div> </div> </section> <section class="section"> <h2>Creating Classes with __init__</h2> <p>The <code>__init__</code> method is Python's constructor that initializes new objects.</p> <img src="assets/image/OOP_Images/Image4.png" alt="Creating Classes with __init__" class="presentation-image"> <div class="code-block"> <span class="code-keyword">class</span> <span class="code-function">house</span>():<br> <span class="code-keyword">def</span> <span class="code-function">__init__</span>(<span class="code-var">self</span>, address, state, Alarm, price):<br> <span class="code-var">self</span>.address = address<br> <span class="code-var">self</span>.state = state<br> <span class="code-var">self</span>.Alarm = Alarm<br> <span class="code-var">self</span>.price = price<br> <br> house1 = house(1234, <span class="code-string">"california"</span>, <span class="code-keyword">False</span>, 300000)<br> house2 = house(5678, <span class="code-string">"texas"</span>, <span class="code-keyword">True</span>, 100000)<br> <br> <span class="code-function">print</span>(house1.state)<br> <span class="code-function">print</span>(house2.price)<br> <br> <span class="code-comment"># Output:</span><br> <span class="code-comment"># california</span><br> <span class="code-comment"># 100000</span> </div> <h3>What is the self Keyword?</h3> <p><code>self</code> refers to the instance of the class. It allows you to access attributes and methods of the object.</p> <img src="assets/image/OOP_Images/Image5.png" alt="Understanding the self keyword" class="presentation-image"> <div class="exercise-container"> <div class="exercise-header">Exercise 2: Using __init__ method</div> <div class="exercise-description"> Improve your Car class by adding an __init__ method to initialize the attributes. </div> <textarea class="code-editor" id="exercise2-editor"># Write your code here # 1. Create a Car class with __init__ method # 2. Initialize brand, model, and year attributes # 3. Create two instances with different values # 4. Print details of both cars class Car: pass # Replace this with your implementation # Create two instances here</textarea> <div class="exercise-buttons"> <button class="exercise-btn" onclick="checkExercise2()">Check Answer</button> <button class="exercise-btn" onclick="resetExercise2()">Reset</button> </div> <div class="exercise-output" id="exercise2-output">Run your code to see output here...</div> </div> <div class="code-block"> <span class="code-keyword">class</span> <span class="code-function">house</span>():<br> <span class="code-keyword">def</span> <span class="code-function">__init__</span>(<span class="code-var">self</span>, address, street, state):<br> <span class="code-var">self</span>.address = address<br> <span class="code-var">self</span>.street = street<br> <span class="code-var">self</span>.state = state<br> <span class="code-var">self</span>.completeAddress = <span class="code-function">str</span>(address) + <span class="code-string">" "</span> + state<br> <br> house = house(1234, <span class="code-string">"california"</span>, <span class="code-string">"awesome road"</span>)<br> <br> <span class="code-function">print</span>(house.completeAddress)<br> <br> <span class="code-comment"># Output:</span><br> <span class="code-comment"># 1234 awesome road</span> </div> </section> <section class="section"> <h2>Instance Variables vs Class Variables</h2> <img src="assets/image/OOP_Images/Image6.png" alt="Instance Variables vs Class Variables" class="presentation-image"> <div class="comparison"> <div class="comparison-item"> <h3>Instance Variables</h3> <p>Unique to each instance of the class</p> <ul> <li>Address</li> <li>State</li> <li>Alarm status</li> <li>Price</li> </ul> <p><em>Like the sofa in each house - can be different</em></p> </div> <div class="comparison-item"> <h3>Class Variables</h3> <p>Shared by all instances of the class</p> <ul> <li>Company name</li> <li>Common features (like a carpet)</li> </ul> <p><em>Like the company name - same for all houses</em></p> </div> </div> <div class="code-block"> <span class="code-keyword">class</span> <span class="code-function">house</span>():<br> <br> <span class="code-comment"># Class variable</span><br> company_name = <span class="code-string">"Awesome building company"</span><br> <br> <span class="code-keyword">def</span> <span class="code-function">__init__</span>(<span class="code-var">self</span>, address, state, Alarm, price):<br> <span class="code-comment"># Instance variables</span><br> <span class="code-var">self</span>.address = address<br> <span class="code-var">self</span>.state = state<br> <span class="code-var">self</span>.Alarm = Alarm<br> <span class="code-var">self</span>.price = price<br> <br> house1 = house(1234, <span class="code-string">"california"</span>, <span class="code-keyword">False</span>, 300000)<br> house2 = house(5678, <span class="code-string">"texas"</span>, <span class="code-keyword">True</span>, 100000)<br> <br> <span class="code-comment"># Accessing class variable</span><br> <span class="code-function">print</span>(house1.company_name)<br> <span class="code-function">print</span>(house2.company_name)<br> <br> <span class="code-comment"># Output:</span><br> <span class="code-comment"># Awesome building company</span> <span class="code-comment"># Awesome building company</span> </div> <div class="exercise-container"> <div class="exercise-header">Exercise 3: Instance vs Class Variables</div> <div class="exercise-description"> Create a Student class with both instance variables (name, grade) and class variables (school_name). </div> <textarea class="code-editor" id="exercise3-editor"># Write your code here # 1. Create a Student class # 2. Add a class variable school_name = "Tech High" # 3. Add an __init__ method with name and grade parameters # 4. Create two student instances # 5. Print both instance data and the class variable class Student: pass # Replace with your implementation # Create instances and print data</textarea> <div class="exercise-buttons"> <button class="exercise-btn" onclick="checkExercise3()">Check Answer</button> <button class="exercise-btn" onclick="resetExercise3()">Reset</button> </div> <div class="exercise-output" id="exercise3-output">Run your code to see output here...</div> </div> </section> <section class="section"> <h2>Methods in OOP</h2> <p>Methods are functions defined inside a class that define the behaviors of objects.</p> <img src="assets/image/OOP_Images/Image7.png" alt="Methods in OOP" class="presentation-image"> <h3>Instance Method Example</h3> <p>Let's create a method to adjust house prices for inflation:</p> <div class="code-block"> <span class="code-keyword">class</span> <span class="code-function">house</span>():<br> <br> company_name = <span class="code-string">"Awesome building company"</span><br> inflation_coefficient = 1.08<br> <br> <span class="code-keyword">def</span> <span class="code-function">__init__</span>(<span class="code-var">self</span>, address, state, Alarm, price):<br> <span class="code-var">self</span>.address = address<br> <span class="code-var">self</span>.state = state<br> <span class="code-var">self</span>.Alarm = Alarm<br> <span class="code-var">self</span>.price = price<br> <br> <span class="code-comment"># Instance method</span><br> <span class="code-keyword">def</span> <span class="code-function">correctPriceMethod</span>(<span class="code-var">self</span>):<br> <span class="code-var">self</span>.price = <span class="code-var">self</span>.price * <span class="code-var">self</span>.inflation_coefficient<br> <br> apartment1 = house(1234, <span class="code-string">"california"</span>, <span class="code-keyword">False</span>, 300000)<br> <br> <span class="code-function">print</span>(<span class="code-string">"Original price:"</span>, apartment1.price)<br> <br> apartment1.correctPriceMethod()<br> <br> <span class="code-function">print</span>(<span class="code-string">"Adjusted price:"</span>, apartment1.price)<br> <br> <span class="code-comment"># Output:</span><br> <span class="code-comment"># Original price: 300000</span><br> <span class="code-comment"># Adjusted price: 324000</span> </div> <div class="exercise-container"> <div class="exercise-header">Exercise 4: Adding Methods to Classes</div> <div class="exercise-description"> Add a method to calculate the age of a car based on its year of manufacture. </div> <textarea class="code-editor" id="exercise4-editor"># Write your code here # 1. Create a Car class with brand, model, and year attributes # 2. Add a method get_car_age() that returns the car's age (2025 - year) # 3. Create an instance and test your method class Car: pass # Replace with your implementation # Create instance and test method</textarea> <div class="exercise-buttons"> <button class="exercise-btn" onclick="checkExercise4()">Check Answer</button> <button class="exercise-btn" onclick="resetExercise4()">Reset</button> </div> <div class="exercise-output" id="exercise4-output">Run your code to see output here...</div> </div> <div class="interactive-demo"> <h3>Try It Yourself: House Price Calculator</h3> <div class="demo-controls"> <button id="createHouse">Create a New House</button> <button id="adjustPrice">Adjust Price for Inflation</button> <button id="reset">Reset</button> </div> <div class="output" id="demoOutput"> Click "Create a New House" to start </div> </div> </section> <!-- New section on Encapsulation --> <section class="section"> <h2>Encapsulation</h2> <p>Encapsulation is the process of preventing clients from accessing certain properties, which can only be accessed through specific methods.</p> <div class="key-concept"> <h3>Key Concept</h3> <p>Private attributes are inaccessible attributes, and information hiding is the process of making particular attributes private. You use two underscores to declare private characteristics.</p> </div> <div class="code-block"> <span class="code-keyword">class</span> <span class="code-function">Book</span>:<br> <span class="code-keyword">def</span> <span class="code-function">__init__</span>(<span class="code-var">self</span>, title, quantity, author, price):<br> <span class="code-var">self</span>.title = title<br> <span class="code-var">self</span>.quantity = quantity<br> <span class="code-var">self</span>.author = author<br> <span class="code-var">self</span>.price = price<br> <span class="code-var">self</span>.__discount = 0.10 <span class="code-comment"># Private attribute</span><br> <br> <span class="code-keyword">def</span> <span class="code-function">__repr__</span>(<span class="code-var">self</span>):<br> <span class="code-keyword">return</span> <span class="code-function">f</span><span class="code-string">"Book: {self.title}, Quantity: {self.quantity}, Author: {self.author}, Price: {self.price}"</span><br> <br> book1 = Book(<span class="code-string">'Book 1'</span>, 12, <span class="code-string">'Author 1'</span>, 120)<br> <br> <span class="code-function">print</span>(book1.title) <span class="code-comment"># Accessible</span><br> <span class="code-function">print</span>(book1.__discount) <span class="code-comment"># Not accessible - will cause an error</span> </div> <h3>Getter and Setter Methods</h3> <p>We use getter and setter methods to access private attributes.</p> <div class="code-block"> <span class="code-keyword">class</span> <span class="code-function">Book</span>:<br> <span class="code-keyword">def</span> <span class="code-function">__init__</span>(<span class="code-var">self</span>, title, quantity, author, price):<br> <span class="code-var">self</span>.title = title<br> <span class="code-var">self</span>.quantity = quantity<br> <span class="code-var">self</span>.author = author<br> <span class="code-var">self</span>.__price = price <span class="code-comment"># Private attribute</span><br> <span class="code-var">self</span>.__discount = <span class="code-keyword">None</span><br> <br> <span class="code-keyword">def</span> <span class="code-function">set_discount</span>(<span class="code-var">self</span>, discount):<br> <span class="code-var">self</span>.__discount = discount<br> <br> <span class="code-keyword">def</span> <span class="code-function">get_price</span>(<span class="code-var">self</span>):<br> <span class="code-keyword">if</span> <span class="code-var">self</span>.__discount:<br> <span class="code-keyword">return</span> <span class="code-var">self</span>.__price * (1-<span class="code-var">self</span>.__discount)<br> <span class="code-keyword">return</span> <span class="code-var">self</span>.__price<br> <br> <span class="code-keyword">def</span> <span class="code-function">__repr__</span>(<span class="code-var">self</span>):<br> <span class="code-keyword">return</span> <span class="code-function">f</span><span class="code-string">"Book: {self.title}, Quantity: {self.quantity}, Author: {self.author}, Price: {self.get_price()}"</span><br> <br> single_book = Book(<span class="code-string">'Two States'</span>, 1, <span class="code-string">'Chetan Bhagat'</span>, 200)<br> bulk_books = Book(<span class="code-string">'Two States'</span>, 25, <span class="code-string">'Chetan Bhagat'</span>, 200)<br> bulk_books.set_discount(0.20) <span class="code-comment"># 20% discount for bulk purchase</span><br> <br> <span class="code-function">print</span>(single_book.get_price()) <span class="code-comment"># 200</span><br> <span class="code-function">print</span>(bulk_books.get_price()) <span class="code-comment"># 160.0</span> </div> <div class="exercise-container"> <div class="exercise-header">Exercise 5: Encapsulation with Bank Account</div> <div class="exercise-description"> Create a BankAccount class with a private balance attribute. Add methods to deposit, withdraw, and check balance. </div> <textarea class="code-editor" id="exercise5-editor"># Write your code here # 1. Create a BankAccount class # 2. Add __init__ method with account_holder parameter # 3. Add a private __balance attribute, initialized to 0 # 4. Add deposit(amount) method to add to balance # 5. Add withdraw(amount) method to subtract from balance (if sufficient funds) # 6. Add get_balance() method to return current balance # 7. Test your class with some transactions class BankAccount: pass # Replace with your implementation # Test your implementation</textarea> <div class="exercise-buttons"> <button class="exercise-btn" onclick="checkExercise5()">Check Answer</button> <button class="exercise-btn" onclick="resetExercise5()">Reset</button> <button class="exercise-btn" onclick="showSolution5()">Show Solution</button> </div> <div class="exercise-output" id="exercise5-output">Run your code to see output here...</div> </div> </section> <!-- New section on Inheritance --> <section class="section"> <h2>Inheritance</h2> <p>Inheritance is regarded as the most significant characteristics of OOP. A class's ability to inherit methods and/or characteristics from another class is known as inheritance.</p> <div class="key-concept"> <h3>Key Concept</h3> <p>The subclass or child class is the class that inherits. The superclass or parent class is the class from which methods and/or attributes are inherited.</p> </div> <div class="code-block"> <span class="code-keyword">class</span> <span class="code-function">Book</span>:<br> <span class="code-keyword">def</span> <span class="code-function">__init__</span>(<span class="code-var">self</span>, title, quantity, author, price):<br> <span class="code-var">self</span>.title = title<br> <span class="code-var">self</span>.quantity = quantity<br> <span class="code-var">self</span>.author = author<br> <span class="code-var">self</span>.__price = price<br> <span class="code-var">self</span>.__discount = <span class="code-keyword">None</span><br> <br> <span class="code-keyword">def</span> <span class="code-function">set_discount</span>(<span class="code-var">self</span>, discount):<br> <span class="code-var">self</span>.__discount = discount<br> <br> <span class="code-keyword">def</span> <span class="code-function">get_price</span>(<span class="code-var">self</span>):<br> <span class="code-keyword">if</span> <span class="code-var">self</span>.__discount:<br> <span class="code-keyword">return</span> <span class="code-var">self</span>.__price * (1-<span class="code-var">self</span>.__discount)<br> <span class="code-keyword">return</span> <span class="code-var">self</span>.__price<br> <br> <span class="code-keyword">def</span> <span class="code-function">__repr__</span>(<span class="code-var">self</span>):<br> <span class="code-keyword">return</span> <span class="code-function">f</span><span class="code-string">"Book: {self.title}, Quantity: {self.quantity}, Author: {self.author}, Price: {self.get_price()}"</span><br> <br> <span class="code-comment"># Novel class inheriting from Book</span><br> <span class="code-keyword">class</span> <span class="code-function">Novel</span>(Book):<br> <span class="code-keyword">def</span> <span class="code-function">__init__</span>(<span class="code-var">self</span>, title, quantity, author, price, pages):<br> <span class="code-function">super</span>().<span class="code-function">__init__</span>(title, quantity, author, price) <span class="code-comment"># Call parent constructor</span><br> <span class="code-var">self</span>.pages = pages<br> <br> <span class="code-comment"># Academic class inheriting from Book</span><br> <span class="code-keyword">class</span> <span class="code-function">Academic</span>(Book):<br> <span class="code-keyword">def</span> <span class="code-function">__init__</span>(<span class="code-var">self</span>, title, quantity, author, price, branch):<br> <span class="code-function">super</span>().<span class="code-function">__init__</span>(title, quantity, author, price) <span class="code-comment"># Call parent constructor</span><br> <span class="code-var">self</span>.branch = branch<br> <br> novel1 = Novel(<span class="code-string">'Two States'</span>, 20, <span class="code-string">'Chetan Bhagat'</span>, 200, 187)<br> novel1.set_discount(0.20)<br> <br> academic1 = Academic(<span class="code-string">'Python Foundations'</span>, 12, <span class="code-string">'PSF'</span>, 655, <span class="code-string">'IT'</span>)<br> <br> <span class="code-function">print</span>(novel1)<br> <span class="code-function">print</span>(academic1) </div> <div class="exercise-container"> <div class="exercise-header">Exercise 6: Inheritance with Animals</div> <div class="exercise-description"> Create an Animal base class and Dog and Cat subclasses that inherit from it. </div> <textarea class="code-editor" id="exercise6-editor"># Write your code here # 1. Create an Animal class with name and species attributes # 2. Add a make_sound() method that prints a generic sound # 3. Create Dog and Cat classes that inherit from Animal # 4. Override make_sound() in each subclass to make animal-specific sounds # 5. Add breed attribute to Dog and color attribute to Cat # 6. Test your classes class Animal: pass # Replace with your implementation class Dog: pass # Replace with your implementation class Cat: pass # Replace with your implementation # Test your implementation</textarea> <div class="exercise-buttons"> <button class="exercise-btn" onclick="checkExercise6()">Check Answer</button> <button class="exercise-btn" onclick="resetExercise6()">Reset</button> <button class="exercise-btn" onclick="showSolution6()">Show Solution</button> </div> <div class="exercise-output" id="exercise6-output">Run your code to see output here...</div> </div> </section> <!-- New section on Polymorphism --> <section class="section"> <h2>Polymorphism</h2> <p>The term 'polymorphism' means 'something that takes on multiple forms.' In OOP, it refers to a subclass's ability to adapt a method that already exists in its superclass to meet its needs.</p> <div class="key-concept"> <h3>Key Concept</h3> <p>A subclass can use a method from its superclass as is or modify it as needed. This allows objects of different types to be treated as instances of the same type through a common interface.</p> </div> <div class="code-block"> <span class="code-keyword">class</span> <span class="code-function">Academic</span>(Book):<br> <span class="code-keyword">def</span> <span class="code-function">__init__</span>(<span class="code-var">self</span>, title, quantity, author, price, branch):<br> <span class="code-function">super</span>().<span class="code-function">__init__</span>(title, quantity, author, price)<br> <span class="code-var">self</span>.branch = branch<br> <br> <span class="code-keyword">def</span> <span class="code-function">__repr__</span>(<span class="code-var">self</span>):<br> <span class="code-keyword">return</span> <span class="code-function">f</span><span class="code-string">"Book: {self.title}, Branch: {self.branch}, Quantity: {self.quantity}, Author: {self.author}, Price: {self.get_price()}"</span><br> <br> novel1 = Novel(<span class="code-string">'Two States'</span>, 20, <span class="code-string">'Chetan Bhagat'</span>, 200, 187)<br> novel1.set_discount(0.20)<br> <br> academic1 = Academic(<span class="code-string">'Python Foundations'</span>, 12, <span class="code-string">'PSF'</span>, 655, <span class="code-string">'IT'</span>)<br> <br> <span class="code-function">print</span>(novel1) <span class="code-comment"># Uses Book's __repr__ method</span><br> <span class="code-function">print</span>(academic1) <span class="code-comment"># Uses Academic's own __repr__ method</span> </div> <div class="exercise-container"> <div class="exercise-header">Exercise 7: Polymorphism with Shapes</div> <div class="exercise-description"> Create a Shape base class and Circle and Rectangle subclasses. Implement area calculation with polymorphism. </div> <textarea class="code-editor" id="exercise7-editor"># Write your code here # 1. Create a Shape class with an area() method that returns 0 # 2. Create Circle and Rectangle classes that inherit from Shape # 3. Override area() in each subclass with appropriate calculations # 4. Add necessary attributes in __init__ methods (radius for Circle, width/height for Rectangle) # 5. Test your classes class Shape: pass # Replace with your implementation class Circle: pass # Replace with your implementation class Rectangle: pass # Replace with your implementation # Test your implementation</textarea> <div class="exercise-buttons"> <button class="exercise-btn" onclick="checkExercise7()">Check Answer</button> <button class="exercise-btn" onclick="resetExercise7()">Reset</button> <button class="exercise-btn" onclick="showSolution7()">Show Solution</button> </div> <div class="exercise-output" id="exercise7-output">Run your code to see output here...</div> </div> </section> <!-- New section on Abstraction --> <section class="section"> <h2>Abstraction</h2> <p>Abstraction isn't supported directly in Python, but calling a magic method allows for abstraction. If an abstract method is declared in a superclass, subclasses that inherit from the superclass must have their own implementation of the method.</p> <div class="key-concept"> <h3>Key Concept</h3> <p>A superclass's abstract method will never be called by its subclasses. But the abstraction aids in the maintenance of a similar structure across all subclasses.</p> </div> <div class="code-block"> <span class="code-keyword">from</span> abc <span class="code-keyword">import</span> ABC, abstractmethod<br> <br> <span class="code-keyword">class</span> <span class="code-function">Book</span>(ABC):<br> <span class="code-keyword">def</span> <span class="code-function">__init__</span>(<span class="code-var">self</span>, title, quantity, author, price):<br> <span class="code-var">self</span>.title = title<br> <span class="code-var">self</span>.quantity = quantity<br> <span class="code-var">self</span>.author = author<br> <span class="code-var">self</span>.__price = price<br> <span class="code-var">self</span>.__discount = <span class="code-keyword">None</span><br> <br> <span class="code-keyword">def</span> <span class="code-function">set_discount</span>(<span class="code-var">self</span>, discount):<br> <span class="code-var">self</span>.__discount = discount<br> <br> <span class="code-keyword">def</span> <span class="code-function">get_price</span>(<span class="code-var">self</span>):<br> <span class="code-keyword">if</span> <span class="code-var">self</span>.__discount:<br> <span class="code-keyword">return</span> <span class="code-var">self</span>.__price * (1-<span class="code-var">self</span>.__discount)<br> <span class="code-keyword">return</span> <span class="code-var">self</span>.__price<br> <br> <span class="code-decorator">@abstractmethod</span><br> <span class="code-keyword">def</span> <span class="code-function">__repr__</span>(<span class="code-var">self</span>):<br> <span class="code-keyword">return</span> <span class="code-function">f</span><span class="code-string">"Book: {self.title}, Quantity: {self.quantity}, Author: {self.author}, Price: {self.get_price()}"</span><br> <br> <span class="code-keyword">class</span> <span class="code-function">Novel</span>(Book):<br> <span class="code-keyword">def</span> <span class="code-function">__init__</span>(<span class="code-var">self</span>, title, quantity, author, price, pages):<br> <span class="code-function">super</span>().<span class="code-function">__init__</span>(title, quantity, author, price)<br> <span class="code-var">self</span>.pages = pages<br> <br> <span class="code-keyword">def</span> <span class="code-function">__repr__</span>(<span class="code-var">self</span>): <span class="code-comment"># Must implement abstract method</span><br> <span class="code-keyword">return</span> <span class="code-function">f</span><span class="code-string">"Book: {self.title}, Quantity: {self.quantity}, Author: {self.author}, Price: {self.get_price()}"</span><br> <br> <span class="code-keyword">class</span> <span class="code-function">Academic</span>(Book):<br> <span class="code-keyword">def</span> <span class="code-function">__init__</span>(<span class="code-var">self</span>, title, quantity, author, price, branch):<br> <span class="code-function">super</span>().<span class="code-function">__init__</span>(title, quantity, author, price)<br> <span class="code-var">self</span>.branch = branch<br> <br> <span class="code-keyword">def</span> <span class="code-function">__repr__</span>(<span class="code-var">self</span>): <span class="code-comment"># Must implement abstract method</span><br> <span class="code-keyword">return</span> <span class="code-function">f</span><span class="code-string">"Book: {self.title}, Branch: {self.branch}, Quantity: {self.quantity}, Author: {self.author}, Price: {self.get_price()}"</span><br> <br> novel1 = Novel(<span class="code-string">'Two States'</span>, 20, <span class="code-string">'Chetan Bhagat'</span>, 200, 187)<br> novel1.set_discount(0.20)<br> <br> academic1 = Academic(<span class="code-string">'Python Foundations'</span>, 12, <span class="code-string">'PSF'</span>, 655, <span class="code-string">'IT'</span>)<br> <br> <span class="code-function">print</span>(novel1)<br> <span class="code-function">print</span>(academic1) </div> </section> <!-- New section on Method Overloading --> <section class="section"> <h2>Method Overloading</h2> <p>Method overloading refers to the use of many methods with the same name that take various numbers of arguments within a single class. Python doesn't support Method Overloading by default.</p> <div class="key-concept"> <h3>Key Concept</h3> <p>Python only remembers the most recent definition of a method. When multiple methods with the same name are defined, the last one overwrites the previous ones.</p> </div> <div class="code-block"> <span class="code-keyword">class</span> <span class="code-function">OverloadingDemo</span>:<br> <span class="code-keyword">def</span> <span class="code-function">add</span>(<span class="code-var">self</span>, x, y):<br> <span class="code-function">print</span>(x+y)<br> <br> <span class="code-keyword">def</span> <span class="code-function">add</span>(<span class="code-var">self</span>, x, y, z):<br> <span class="code-function">print</span>(x+y+z)<br> <br> obj = OverloadingDemo()<br> obj.add(2, 3) <span class="code-comment"># Error! Missing argument z</span> </div> <p>To achieve method overloading in Python, we can use default parameters:</p> <div class="code-block"> <span class="code-keyword">class</span> <span class="code-function">Calculator</span>:<br> <span class="code-keyword">def</span> <span class="code-function">add</span>(<span class="code-var">self</span>, x, y, z=0):<br> <span class="code-keyword">return</span> x + y + z<br> <br> calc = Calculator()<br> <span class="code-function">print</span>(calc.add(2, 3)) <span class="code-comment"># 5</span><br> <span class="code-function">print</span>(calc.add(2, 3, 4)) <span class="code-comment"># 9</span> </div> </section> <!-- New section on Method Overriding --> <section class="section"> <h2>Method Overriding</h2> <p>When a method with the same name and arguments is used in both a derived class and a base or super class, we say that the derived class method "overrides" the method provided in the base class.</p> <div class="key-concept"> <h3>Key Concept</h3> <p>When the overridden method gets called, the derived class's method is always invoked. The method that was used in the base class is now hidden.</p> </div> <div class="code-block"> <span class="code-keyword">class</span> <span class="code-function">ParentClass</span>:<br> <span class="code-keyword">def</span> <span class="code-function">call_me</span>(<span class="code-var">self</span>):<br> <span class="code-function">print</span>(<span class="code-string">"I am parent class"</span>)<br> <br> <span class="code-keyword">class</span> <span class="code-function">ChildClass</span>(ParentClass):<br> <span class="code-keyword">def</span> <span class="code-function">call_me</span>(<span class="code-var">self</span>):<br> <span class="code-function">print</span>(<span class="code-string">"I am child class"</span>)<br> <br> pobj = ParentClass()<br> pobj.call_me() <span class="code-comment"># Output: I am parent class</span><br> <br> cobj = ChildClass()<br> cobj.call_me() <span class="code-comment"># Output: I am child class</span> </div> <p>We can invoke the parent class's method from the child class using <code>super()</code>:</p> <div class="code-block"> <span class="code-keyword">class</span> <span class="code-function">ParentClass</span>:<br> <span class="code-keyword">def</span> <span class="code-function">call_me</span>(<span class="code-var">self</span>):<br> <span class="code-function">print</span>(<span class="code-string">"I am parent class"</span>)<br> <br> <span class="code-keyword">class</span> <span class="code-function">ChildClass</span>(ParentClass):<br> <span class="code-keyword">def</span> <span class="code-function">call_me</span>(<span class="code-var">self</span>):<br> <span class="code-function">print</span>(<span class="code-string">"I am child class"</span>)<br> <span class="code-function">super</span>().<span class="code-function">call_me</span>() <span class="code-comment"># Call parent method</span><br> <br> pobj = ParentClass()<br> pobj.call_me() <span class="code-comment"># Output: I am parent class</span><br> <br> cobj = ChildClass()<br> cobj.call_me() <span class="code-comment"># Output: I am child class \n I am parent class</span> </div> <div class="exercise-container"> <div class="exercise-header">Exercise 8: Method Overriding</div> <div class="exercise-description"> Create a Vehicle class and a Car subclass that overrides a method from the parent class. </div> <textarea class="code-editor" id="exercise8-editor"># Write your code here # 1. Create a Vehicle class with start_engine() method that prints "Vehicle engine started" # 2. Create a Car class that inherits from Vehicle # 3. Override start_engine() in Car to print "Car engine started" # 4. Add a call to super().start_engine() in the Car's start_engine method # 5. Test both classes class Vehicle: pass # Replace with your implementation class Car: pass # Replace with your implementation # Test your implementation</textarea> <div class="exercise-buttons"> <button class="exercise-btn" onclick="checkExercise8()">Check Answer</button> <button class="exercise-btn" onclick="resetExercise8()">Reset</button> <button class="exercise-btn" onclick="showSolution8()">Show Solution</button> </div> <div class="exercise-output" id="exercise8-output">Run your code to see output here...</div> </div> </section> <section class="section"> <h2>OOP in Different Languages</h2> <img src="assets/image/OOP_Images/Image9.png" alt="OOP in Different Languages" class="presentation-image"> <div class="comparison"> <div class="comparison-item"> <h3>Java</h3> <p>Designed specifically for OOP. You create classes and objects to structure your code.</p> <p><em>Like creating blueprints and then building with those blueprints.</em></p> </div> <div class="comparison-item"> <h3>C</h3> <p>Works in a more procedural manner. Following a recipe step by step instead of using blueprints.</p> </div> <div class="comparison-item"> <h3>Python</h3> <p>A flexible language that supports both OOP and procedural programming.</p> <p>You can use classes for OOP or give straightforward instructions like a to-do list.</p> </div> </div> </section> <section class="section"> <h2>Summary</h2> <p>Object-Oriented Programming is a powerful paradigm that helps you:</p> <ul> <li>Organize code in a logical way</li> <li>Reuse code through inheritance</li> <li>Protect data through encapsulation</li> <li>Create flexible code through polymorphism</li> <li>Manage complexity through abstraction</li> </ul> <p>In Python, you implement OOP using:</p> <ul> <li><strong>Classes</strong> as blueprints</li> <li><strong>Objects</strong> as instances of classes</li> <li><strong>__init__</strong> as the constructor method</li> <li><strong>self</strong> to refer to the current instance</li> <li><strong>Methods</strong> to define behaviors</li> </ul> <div class="quote"> "Objects are like people. They're living, breathing things that have knowledge inside them about how to do things and have memory inside them so they can remember things." - Steve Jobs </div> </section> <footer> <p>Interactive OOP Presentation based on the article by Tiago Capelo Monteiro</p> <p>Created with HTML, CSS, and JavaScript</p> </footer> </div> <script> // Interactive demo functionality document.addEventListener('DOMContentLoaded', function() { let currentHouse = null; const output = document.getElementById('demoOutput'); document.getElementById('createHouse').addEventListener('click', function() { const states = ['California', 'Texas', 'Florida', 'New York', 'Colorado']; const randomState = states[Math.floor(Math.random() * states.length)]; const randomPrice = Math.floor(Math.random() * 400000) + 100000; const hasAlarm = Math.random() > 0.5; currentHouse = { address: Math.floor(Math.random() * 9000) + 1000, state: randomState, alarm: hasAlarm, price: randomPrice }; output.innerHTML = ` <strong>New House Created!</strong><br> Address: ${currentHouse.address}<br> State: ${currentHouse.state}<br> Alarm System: ${currentHouse.alarm ? 'Yes' : 'No'}<br> Price: $${currentHouse.price.toLocaleString()} `; }); document.getElementById('adjustPrice').addEventListener('click', function() { if (!currentHouse) { output.innerHTML = 'Please create a house first!'; return; } const inflation = 1.08; const oldPrice = currentHouse.price; currentHouse.price = Math.round(currentHouse.price * inflation); output.innerHTML = ` <strong>Price Adjusted for Inflation (8%)</strong><br> Address: ${currentHouse.address}<br> State: ${currentHouse.state}<br> Alarm System: ${currentHouse.alarm ? 'Yes' : 'No'}<br> Old Price: $${oldPrice.toLocaleString()}<br> <strong>New Price: $${currentHouse.price.toLocaleString()}</strong> `; }); document.getElementById('reset').addEventListener('click', function() { currentHouse = null; output.innerHTML = 'Click "Create a New House" to start'; }); }); // Exercise checking functions function evaluateCode(code) { try { // Create a safe evaluation context const consoleOutput = []; const mockConsole = { log: (...args) => { consoleOutput.push(args.join(' ')); }, error: (...args) => { consoleOutput.push("ERROR: " + args.join(' ')); } }; // Create a function with limited scope const func = new Function('console', code); func(mockConsole); return { success: true, output: consoleOutput.join('\n') }; } catch (error) { return { success: false, output: "Error: " + error.message }; } } // Exercise 1: Creating a simple class function checkExercise1() { const code = document.getElementById('exercise1-editor').value; const outputElement = document.getElementById('exercise1-output'); if (code.trim() === '' || code.includes('pass # Replace this with your implementation')) { outputElement.innerHTML = '<span class="error-message">Please write your code first!</span>'; return; } const result = evaluateCode(code); if (result.success) { outputElement.innerHTML = `<span class="success-message">Great job! Your code ran successfully.\n\nOutput:\n${result.output}</span>`; } else { outputElement.innerHTML = `<span class="error-message">${result.output}</span>`; } } function resetExercise1() { document.getElementById('exercise1-editor').value = `# Write your code here # 1. Create a Car class with __init__ method # 2. Add brand, model, and year parameters # 3. Create an instance of your Car class # 4. Print the car's details class Car: pass # Replace this with your implementation # Create an instance here`; document.getElementById('exercise1-output').innerHTML = 'Run your code to see output here...'; } // Exercise 2: Using __init__ method function checkExercise2() { const code = document.getElementById('exercise2-editor').value; const outputElement = document.getElementById('exercise2-output'); if (code.trim() === '' || code.includes('pass # Replace this with your implementation')) { outputElement.innerHTML = '<span class="error-message">Please write your code first!</span>'; return; } const result = evaluateCode(code); if (result.success) { outputElement.innerHTML = `<span class="success-message">Well done! Your code executed correctly.\n\nOutput:\n${result.output}</span>`; } else { outputElement.innerHTML = `<span class="error-message">${result.output}</span>`; } } function resetExercise2() { document.getElementById('exercise2-editor').value = `# Write your code here # 1. Create a Car class with __init__ method # 2. Initialize brand, model, and year attributes # 3. Create two instances with different values # 4. Print details of both cars class Car: pass # Replace this with your implementation # Create two instances here`; document.getElementById('exercise2-output').innerHTML = 'Run your code to see output here...'; } // Exercise 3: Instance vs Class Variables function checkExercise3() { const code = document.getElementById('exercise3-editor').value; const outputElement = document.getElementById('exercise3-output'); if (code.trim() === '' || code.includes('pass # Replace with your implementation')) { outputElement.innerHTML = '<span class="error-message">Please write your code first!</span>'; return; } const result = evaluateCode(code); if (result.success) { outputElement.innerHTML = `<span class="success-message">Excellent! Your implementation is correct.\n\nOutput:\n${result.output}</span>`; } else { outputElement.innerHTML = `<span class="error-message">${result.output}</span>`; } } function resetExercise3() { document.getElementById('exercise3-editor').value = `# Write your code here # 1. Create a Student class # 2. Add a class variable school_name = "Tech High" # 3. Add an __init__ method with name and grade parameters # 4. Create two student instances # 5. Print both instance data and the class variable class Student: pass # Replace with your implementation # Create instances and print data`; document.getElementById('exercise3-output').innerHTML = 'Run your code to see output here...'; } // Exercise 4: Creating Methods function checkExercise4() { const code = document.getElementById('exercise4-editor').value; const outputElement = document.getElementById('exercise4-output'); if (code.trim() === '' || code.includes('pass # Replace with your implementation')) { outputElement.innerHTML = '<span class="error-message">Please write your code first!</span>'; return; } const result = evaluateCode(code); if (result.success) { outputElement.innerHTML = `<span class="success-message">Perfect! Your method works correctly.\n\nOutput:\n${result.output}</span>`; } else { outputElement.innerHTML = `<span class="error-message">${result.output}</span>`; } } function resetExercise4() { document.getElementById('exercise4-editor').value = `# Write your code here # 1. Create a Car class with brand, model, and year attributes # 2. Add a method get_car_age() that returns the car's age (2025 - year) # 3. Create an instance and test your method class Car: pass # Replace with your implementation # Create instance and test method`; document.getElementById('exercise4-output').innerHTML = 'Run your code to see output here...'; } // Solution functions function showSolution1() { document.getElementById('exercise1-editor').value = "# Sample solution for Exercise 1\\n" + "class Car:\\n" + " def __init__(self, brand, model, year):\\n" + " self.brand = brand\\n" + " self.model = model\\n" + " self.year = year\\n\\n" + "# Create an instance\\n" + "my_car = Car(\\"Toyota\\", \\"Camry\\", 2020)\\n" + "print(f\\"I have a {my_car.year} {my_car.brand} {my_car.model}\\")"; } function showSolution2() { document.getElementById('exercise2-editor').value = "# Sample solution for Exercise 2\\n" + "class Car:\\n" + " def __init__(self, brand, model, year):\\n" + " self.brand = brand\\n" + " self.model = model\\n" + " self.year = year\\n\\n" + "# Create two instances\\n" + "car1 = Car(\\"Toyota\\", \\"Camry\\", 2020)\\n" + "car2 = Car(\\"Honda\\", \\"Civic\\", 2018)\\n\\n" + "print(f\\"Car 1: {car1.year} {car1.brand} {car1.model}\\")\\n" + "print(f\\"Car 2: {car2.year} {car2.brand} {car2.model}\\")"; } function showSolution3() { document.getElementById('exercise3-editor').value = "# Sample solution for Exercise 3\\n" + "class Student:\\n" + " school_name = \\"Tech High\\" # Class variable\\n\\n" + " def __init__(self, name, grade):\\n" + " self.name = name # Instance variables\\n" + " self.grade = grade\\n\\n" + "# Create instances\\n" + "student1 = Student(\\"Alice\\", \\"A\\")\\n" + "student2 = Student(\\"Bob\\", \\"B\\")\\n\\n" + "# Print data\\n" + "print(f\\"{student1.name} from {Student.school_name} got grade {student1.grade}\\")\\n" + "print(f\\"{student2.name} from {Student.school_name} got grade {student2.grade}\\")"; } function showSolution4() { document.getElementById('exercise4-editor').value = "# Sample solution for Exercise 4\\n" + "class Car:\\n" + " def __init__(self, brand, model, year):\\n" + " self.brand = brand\\n" + " self.model = model\\n" + " self.year = year\\n\\n" + " def get_car_age(self):\\n" + " current_year = 2025\\n" + " return current_year - self.year\\n\\n" + "# Create instance and test method\\n" + "my_car = Car(\\"Toyota\\", \\"Camry\\", 2020)\\n" + "print(f\\"My car is {my_car.get_car_age()} years old\\")"; } function resetExercise4() { document.getElementById('exercise4-editor').value = `# Write your code here # 1. Create a Car class with brand, model, and year attributes # 2. Add a method get_car_age() that returns the car's age (2025 - year) # 3. Create an instance and test your method class Car: pass # Replace with your implementation # Create instance and test method`; document.getElementById('exercise4-output').innerHTML = 'Run your code to see output here...'; } // Exercise 5: Encapsulation with Bank Account // Solution functions function showSolution1() { document.getElementById('exercise1-editor').value = "# Sample solution for Exercise 1\\n" + "class Car:\\n" + " def __init__(self, brand, model, year):\\n" + " self.brand = brand\\n" + " self.model = model\\n" + " self.year = year\\n\\n" + "# Create an instance\\n" + "my_car = Car(\\"Toyota\\", \\"Camry\\", 2020)\\n" + "print(f\\"I have a {my_car.year} {my_car.brand} {my_car.model}\\")"; } function showSolution2() { document.getElementById('exercise2-editor').value = "# Sample solution for Exercise 2\\n" + "class Car:\\n" + " def __init__(self, brand, model, year):\\n" + " self.brand = brand\\n" + " self.model = model\\n" + " self.year = year\\n\\n" + "# Create two instances\\n" + "car1 = Car(\\"Toyota\\", \\"Camry\\", 2020)\\n" + "car2 = Car(\\"Honda\\", \\"Civic\\", 2018)\\n\\n" + "print(f\\"Car 1: {car1.year} {car1.brand} {car1.model}\\")\\n" + "print(f\\"Car 2: {car2.year} {car2.brand} {car2.model}\\")"; } function showSolution3() { document.getElementById('exercise3-editor').value = "# Sample solution for Exercise 3\\n" + "class Student:\\n" + " school_name = \\"Tech High\\" # Class variable\\n\\n" + " def __init__(self, name, grade):\\n" + " self.name = name # Instance variables\\n" + " self.grade = grade\\n\\n" + "# Create instances\\n" + "student1 = Student(\\"Alice\\", \\"A\\")\\n" + "student2 = Student(\\"Bob\\", \\"B\\")\\n\\n" + "# Print data\\n" + "print(f\\"{student1.name} from {Student.school_name} got grade {student1.grade}\\")\\n" + "print(f\\"{student2.name} from {Student.school_name} got grade {student2.grade}\\")"; } function showSolution4() { document.getElementById('exercise4-editor').value = "# Sample solution for Exercise 4\\n" + "class Car:\\n" + " def __init__(self, brand, model, year):\\n" + " self.brand = brand\\n" + " self.model = model\\n" + " self.year = year\\n\\n" + " def get_car_age(self):\\n" + " current_year = 2025\\n" + " return current_year - self.year\\n\\n" + "# Create instance and test method\\n" + "my_car = Car(\\"Toyota\\", \\"Camry\\", 2020)\\n" + "print(f\\"My car is {my_car.get_car_age()} years old\\")"; } // Exercise 5: Encapsulation with Bank Account function checkExercise5() { const code = document.getElementById('exercise5-editor').value; const outputElement = document.getElementById('exercise5-output'); if (code.trim() === '' || code.includes('pass # Replace with your implementation')) { outputElement.innerHTML = '<span class="error-message">Please write your code first!</span>'; return; } const result = evaluateCode(code); if (result.success) { outputElement.innerHTML = `<span class="success-message">Great job! Your encapsulation implementation is working.\\n\\nOutput:\\n${result.output}</span>`; } else { outputElement.innerHTML = `<span class="error-message">${result.output}</span>`; } } function resetExercise5() { document.getElementById('exercise5-editor').value = `# Write your code here # 1. Create a BankAccount class # 2. Add __init__ method with account_holder parameter # 3. Add a private __balance attribute, initialized to 0 # 4. Add deposit(amount) method to add to balance # 5. Add withdraw(amount) method to subtract from balance (if sufficient funds) # 6. Add get_balance() method to return current balance # 7. Test your class with some transactions class BankAccount: pass # Replace with your implementation # Test your implementation`; document.getElementById('exercise5-output').innerHTML = 'Run your code to see output here...'; } // Exercise 6: Inheritance with Animals function checkExercise6() { const code = document.getElementById('exercise6-editor').value; const outputElement = document.getElementById('exercise6-output'); if (code.trim() === '' || code.includes('pass # Replace with your implementation')) { outputElement.innerHTML = '<span class="error-message">Please write your code first!</span>'; return; } const result = evaluateCode(code); if (result.success) { outputElement.innerHTML = `<span class="success-message">Excellent! Your inheritance implementation is correct.\\n\\nOutput:\\n${result.output}</span>`; } else { outputElement.innerHTML = `<span class="error-message">${result.output}</span>`; } } function resetExercise6() { document.getElementById('exercise6-editor').value = `# Write your code here # 1. Create an Animal class with name and species attributes # 2. Add a make_sound() method that prints a generic sound # 3. Create Dog and Cat classes that inherit from Animal # 4. Override make_sound() in each subclass to make animal-specific sounds # 5. Add breed attribute to Dog and color attribute to Cat # 6. Test your classes class Animal: pass # Replace with your implementation class Dog: pass # Replace with your implementation class Cat: pass # Replace with your implementation # Test your implementation`; document.getElementById('exercise6-output').innerHTML = 'Run your code to see output here...'; } // Exercise 7: Polymorphism with Shapes function checkExercise7() { const code = document.getElementById('exercise7-editor').value; const outputElement = document.getElementById('exercise7-output'); if (code.trim() === '' || code.includes('pass # Replace with your implementation')) { outputElement.innerHTML = '<span class="error-message">Please write your code first!</span>'; return; } const result = evaluateCode(code); if (result.success) { outputElement.innerHTML = `<span class="success-message">Perfect! Your polymorphism implementation works correctly.\\n\\nOutput:\\n${result.output}</span>`; } else { outputElement.innerHTML = `<span class="error-message">${result.output}</span>`; } } function resetExercise7() { document.getElementById('exercise7-editor').value = `# Write your code here # 1. Create a Shape class with an area() method that returns 0 # 2. Create Circle and Rectangle classes that inherit from Shape # 3. Override area() in each subclass with appropriate calculations # 4. Add necessary attributes in __init__ methods (radius for Circle, width/height for Rectangle) # 5. Test your classes class Shape: pass # Replace with your implementation class Circle: pass # Replace with your implementation class Rectangle: pass # Replace with your implementation # Test your implementation`; document.getElementById('exercise7-output').innerHTML = 'Run your code to see output here...'; } // Exercise 8: Method Overriding function checkExercise8() { const code = document.getElementById('exercise8-editor').value; const outputElement = document.getElementById('exercise8-output'); if (code.trim() === '' || code.includes('pass # Replace with your implementation')) { outputElement.innerHTML = '<span class="error-message">Please write your code first!</span>'; return; } const result = evaluateCode(code); if (result.success) { outputElement.innerHTML = `<span class="success-message">Well done! Your method overriding implementation is correct.\\n\\nOutput:\\n${result.output}</span>`; } else { outputElement.innerHTML = `<span class="error-message">${result.output}</span>`; } } function resetExercise8() { document.getElementById('exercise8-editor').value = `# Write your code here # 1. Create a Vehicle class with start_engine() method that prints "Vehicle engine started" # 2. Create a Car class that inherits from Vehicle # 3. Override start_engine() in Car to print "Car engine started" # 4. Add a call to super().start_engine() in the Car's start_engine method # 5. Test both classes class Vehicle: pass # Replace with your implementation class Car: pass # Replace with your implementation # Test your implementation`; document.getElementById('exercise8-output').innerHTML = 'Run your code to see output here...'; } // Solution functions for new exercises function showSolution5() { document.getElementById('exercise5-editor').value = "# Sample solution for Exercise 5\\n" + "class BankAccount:\\n" + " def __init__(self, account_holder):\\n" + " self.account_holder = account_holder\\n" + " self.__balance = 0 # Private attribute\\n\\n" + " def deposit(self, amount):\\n" + " if amount > 0:\\n" + " self.__balance += amount\\n" + " print(f\\"Deposited ${amount}. New balance: ${self.__balance}\\")\\n" + " else:\\n" + " print(\\"Deposit amount must be positive\\")\\n\\n" + " def withdraw(self, amount):\\n" + " if amount > 0 and amount <= self.__balance:\\n" + " self.__balance -= amount\\n" + " print(f\\"Withdrew ${amount}. New balance: ${self.__balance}\\")\\n" + " else:\\n" + " print(\\"Invalid withdrawal amount\\")\\n\\n" + " def get_balance(self):\\n" + " return self.__balance\\n\\n" + "# Test the implementation\\n" + "account = BankAccount(\\"John Doe\\")\\n" + "account.deposit(100)\\n" + "account.withdraw(50)\\n" + "print(f\\"Final balance: ${account.get_balance()}\\")"; } function showSolution6() { document.getElementById('exercise6-editor').value = "# Sample solution for Exercise 6\\n" + "class Animal:\\n" + " def __init__(self, name, species):\\n" + " self.name = name\\n" + " self.species = species\\n\\n" + " def make_sound(self):\\n" + " print(\\"Some generic animal sound\\")\\n\\n" + "class Dog(Animal):\\n" + " def __init__(self, name, breed):\\n" + " super().__init__(name, \\"Dog\\")\\n" + " self.breed = breed\\n\\n" + " def make_sound(self):\\n" + " print(\\"Woof! Woof!\\")\\n\\n" + "class Cat(Animal):\\n" + " def __init__(self, name, color):\\n" + " super().__init__(name, \\"Cat\\")\\n" + " self.color = color\\n\\n" + " def make_sound(self):\\n" + " print(\\"Meow!\\")\\n\\n" + "# Test the implementation\\n" + "dog = Dog(\\"Buddy\\", \\"Golden Retriever\\")\\n" + "cat = Cat(\\"Whiskers\\", \\"Orange\\")\\n\\n" + "print(f\\"{dog.name} is a {dog.breed} {dog.species}\\")\\n" + "dog.make_sound()\\n\\n" + "print(f\\"{cat.name} is a {cat.color} {cat.species}\\")\\n" + "cat.make_sound()"; } function showSolution7() { document.getElementById('exercise7-editor').value = "# Sample solution for Exercise 7\\n" + "import math\\n\\n" + "class Shape:\\n" + " def area(self):\\n" + " return 0\\n\\n" + "class Circle(Shape):\\n" + " def __init__(self, radius):\\n" + " self.radius = radius\\n\\n" + " def area(self):\\n" + " return math.pi * self.radius ** 2\\n\\n" + "class Rectangle(Shape):\\n" + " def __init__(self, width, height):\\n" + " self.width = width\\n" + " self.height = height\\n\\n" + " def area(self):\\n" + " return self.width * self.height\\n\\n" + "# Test the implementation\\n" + "circle = Circle(5)\\n" + "rectangle = Rectangle(4, 6)\\n\\n" + "print(f\\"Circle area: {circle.area():.2f}\\")\\n" + "print(f\\"Rectangle area: {rectangle.area()}\\")"; } function showSolution8() { document.getElementById('exercise8-editor').value = "# Sample solution for Exercise 8\\n" + "class Vehicle:\\n" + " def start_engine(self):\\n" + " print(\\"Vehicle engine started\\")\\n\\n" + "class Car(Vehicle):\\n" + " def start_engine(self):\\n" + " print(\\"Car engine started\\")\\n" + " super().start_engine() # Call parent method\\n\\n" + "# Test the implementation\\n" + "vehicle = Vehicle()\\n" + "car = Car()\\n\\n" + "print(\\"Starting vehicle engine:\\")\\n" + "vehicle.start_engine()\\n\\n" + "print(\\"Starting car engine:\\")\\n" + "car.start_engine()"; } </script> </body> </html>