/
ict
/
techshare_sites
Обзор
Документация
Войти
/
ict
/
techshare_sites
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
Object-Oriented-Programming-in-Python_v2.html
1 657 строк
86 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; } body { background: linear-gradient(135deg, #1a2a6c, #b21f1f, #fdbb2d); color: #333; line-height: 1.6; overflow-x: hidden; } .code-block-container { position: relative; margin: 15px 0; } .copy-button { position: absolute; top: 10px; right: 10px; background-color: #4CAF50; color: white; border: none; padding: 5px 10px; cursor: pointer; border-radius: 4px; font-size: 12px; z-index: 10; } .copy-button:hover { background-color: #45a049; } .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; } .analogy h4 { color: #1a2a6c; margin-bottom: 10px; } 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; } /* Drag and Drop Exercise Styles */ .drag-drop-container { background-color: #f9f9f9; border: 2px dashed #4682b4; border-radius: 8px; padding: 20px; margin: 20px 0; } .drag-drop-instructions { margin-bottom: 15px; font-weight: bold; } .code-blocks-container { display: flex; flex-wrap: wrap; gap: 10px; margin-bottom: 20px; } .code-block-draggable { background-color: #2d2d2d; color: #f8f8f2; padding: 10px; border-radius: 4px; cursor: move; font-family: 'Courier New', monospace; user-select: none; } .code-block-draggable.dragging { opacity: 0.5; } .drop-zone { background-color: #fff; border: 2px dashed #4682b4; border-radius: 8px; min-height: 200px; padding: 15px; margin-bottom: 15px; } .drop-zone.highlight { background-color: #e6f3ff; border-color: #1a2a6c; } .drag-drop-buttons { display: flex; gap: 10px; } .key-concept { background-color: #fff8e1; border-left: 4px solid #ffc107; padding: 15px; margin: 15px 0; border-radius: 0 4px 4px 0; } 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> <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> <h3>Creating Classes Manually</h3> <h2>Creating Classes with __init__</h2> <p>The <code>__init__</code> method is Python's constructor that initializes new objects.</p> <div class="code-block-container"> <button class="copy-button" onclick="copyCode(this)">Copy</button> <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> </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> <div class="code-block-container"> <button class="copy-button" onclick="copyCode(this)">Copy</button> <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> <div class="code-block"> <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> <div class="code-block-container"> <button class="copy-button" onclick="copyCode(this)">Copy</button> <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> <img src="assets/image/OOP_Images/Image5.png" alt="Understanding the self keyword" 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, 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> <div class="drag-drop-container"> <div class="drag-drop-instructions">Drag and drop the code blocks to create a complete class definition:</div> <div class="code-blocks-container" id="drag-container-1"> <div class="code-block-draggable" draggable="true">class Dog:</div> <div class="code-block-draggable" draggable="true">def __init__(self, name, breed):</div> <div class="code-block-draggable" draggable="true">self.name = name</div> <div class="code-block-draggable" draggable="true">self.breed = breed</div> <div class="code-block-draggable" draggable="true">my_dog = Dog("Buddy", "Golden Retriever")</div> <div class="code-block-draggable" draggable="true">print(my_dog.name)</div> </div> <div class="drop-zone" id="drop-zone-1"></div> <div class="drag-drop-buttons"> <button class="exercise-btn" onclick="checkDragDrop1()">Check Answer</button> <button class="exercise-btn" onclick="resetDragDrop1()">Reset</button> </div> <div class="exercise-output" id="drag-output-1">Arrange the code blocks in the correct order...</div> </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> </ul> </div> <div class="comparison-item"> <h3>Class Variables</h3> <p>Shared among all instances of the class</p> <ul> <li>Company Name</li> </ul> </div> </div> </section> <section class="section"> <h2>OOP in Different Languages</h2> <p>Object-oriented programming can be implemented in various programming languages:</p> <p>Object-oriented programming can be implemented in various programming languages:</p> <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 2: 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="exercise2-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="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> </section> <section class="section"> <h2>Methods in OOP</h2> <p>Methods are functions defined inside a class that define the behaviors of objects.</p> <h3>Instance Method Example</h3> <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 3: 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="exercise3-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="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> <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> <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="drag-drop-container"> <div class="drag-drop-instructions">Drag and drop the code blocks to create a BankAccount class with encapsulation:</div> <div class="code-blocks-container" id="drag-container-2"> <div class="code-block-draggable" draggable="true">class BankAccount:</div> <div class="code-block-draggable" draggable="true">def __init__(self, account_holder):</div> <div class="code-block-draggable" draggable="true">self.account_holder = account_holder</div> <div class="code-block-draggable" draggable="true">self.__balance = 0</div> <div class="code-block-draggable" draggable="true">def deposit(self, amount):</div> <div class="code-block-draggable" draggable="true">if amount > 0:</div> <div class="code-block-draggable" draggable="true">self.__balance += amount</div> <div class="code-block-draggable" draggable="true">def withdraw(self, amount):</div> <div class="code-block-draggable" draggable="true">if amount > 0 and amount <= self.__balance:</div> <div class="code-block-draggable" draggable="true">self.__balance -= amount</div> <div class="code-block-draggable" draggable="true">def get_balance(self):</div> <div class="code-block-draggable" draggable="true">return self.__balance</div> </div> <div class="drop-zone" id="drop-zone-2"></div> <div class="drag-drop-buttons"> <button class="exercise-btn" onclick="checkDragDrop2()">Check Answer</button> <button class="exercise-btn" onclick="resetDragDrop2()">Reset</button> </div> <div class="exercise-output" id="drag-output-2">Arrange the code blocks in the correct order...</div> </div> </section> <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="drag-drop-container"> <div class="drag-drop-instructions">Drag and drop the code blocks to create an inheritance hierarchy:</div> <div class="code-blocks-container" id="drag-container-3"> <div class="code-block-draggable" draggable="true">class Animal:</div> <div class="code-block-draggable" draggable="true">def __init__(self, name):</div> <div class="code-block-draggable" draggable="true">self.name = name</div> <div class="code-block-draggable" draggable="true">def speak(self):</div> <div class="code-block-draggable" draggable="true">pass</div> <div class="code-block-draggable" draggable="true">class Dog(Animal):</div> <div class="code-block-draggable" draggable="true">def speak(self):</div> <div class="code-block-draggable" draggable="true">return "Woof!"</div> <div class="code-block-draggable" draggable="true">class Cat(Animal):</div> <div class="code-block-draggable" draggable="true">def speak(self):</div> <div class="code-block-draggable" draggable="true">return "Meow!"</div> </div> <div class="drop-zone" id="drop-zone-3"></div> <div class="drag-drop-buttons"> <button class="exercise-btn" onclick="checkDragDrop3()">Check Answer</button> <button class="exercise-btn" onclick="resetDragDrop3()">Reset</button> </div> <div class="exercise-output" id="drag-output-3">Arrange the code blocks in the correct order...</div> </div> </section> <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 4: 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="exercise4-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="checkExercise4()">Check Answer</button> <button class="exercise-btn" onclick="resetExercise4()">Reset</button> <button class="exercise-btn" onclick="showSolution4()">Show Solution</button> </div> <div class="exercise-output" id="exercise4-output">Run your code to see output here...</div> </div> </section> <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> <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> <h3>The __repr__ Method</h3> <p>The <code>__repr__</code> method is a special method that defines the "official" string representation of an object.</p> <img src="assets/image/OOP_Images/Image8.png" alt="Interactive Demo" class="presentation-image"> <div class="code-block"> <span class="code-keyword">class</span> <span class="code-function">Point</span>:<br> <span class="code-keyword">def</span> <span class="code-function">__init__</span>(<span class="code-var">self</span>, x, y):<br> <span class="code-var">self</span>.x = x<br> <span class="code-var">self</span>.y = y<br> <br> <span class="code-keyword">def</span> <span class="code-function">__repr__</span>(<span class="code-var">self</span>):<br> <span class="code-function">return</span> <span class="code-string">"Point({}, {})"</span>.<span class="code-function">format</span>(<span class="code-var">self</span>.x, <span class="code-var">self</span>.y)<br> <h3>The __str__ Method</h3> <p>The <code>__str__</code> method is a special method that defines the "informal" or nicely printable string representation of an object.</p> <img src="assets/image/OOP_Images/Image8.png" alt="Interactive Demo" class="presentation-image"> <div class="code-block"> <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> <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="drag-drop-container"> <div class="drag-drop-instructions">Drag and drop the code blocks to demonstrate method overriding:</div> <div class="code-blocks-container" id="drag-container-4"> <div class="code-block-draggable" draggable="true">class Vehicle:</div> <div class="code-block-draggable" draggable="true">def start_engine(self):</div> <div class="code-block-draggable" draggable="true">print("Vehicle engine started")</div> <div class="code-block-draggable" draggable="true">class Car(Vehicle):</div> <div class="code-block-draggable" draggable="true">def start_engine(self):</div> <div class="code-block-draggable" draggable="true">print("Car engine started")</div> <div class="code-block-draggable" draggable="true">super().start_engine()</div> </div> <div class="drop-zone" id="drop-zone-4"></div> <div class="drag-drop-buttons"> <button class="exercise-btn" onclick="checkDragDrop4()">Check Answer</button> <button class="exercise-btn" onclick="resetDragDrop4()">Reset</button> </div> <div class="exercise-output" id="drag-output-4">Arrange the code blocks in the correct order...</div> </div> </section> <section class="section"> <h2>OOP in Different Languages</h2> <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'; }); // Initialize drag and drop functionality initializeDragAndDrop(); }); // Drag and Drop functionality function initializeDragAndDrop() { const draggables = document.querySelectorAll('.code-block-draggable'); const dropZones = document.querySelectorAll('.drop-zone'); draggables.forEach(draggable => { draggable.addEventListener('dragstart', () => { draggable.classList.add('dragging'); }); draggable.addEventListener('dragend', () => { draggable.classList.remove('dragging'); }); }); dropZones.forEach(zone => { zone.addEventListener('dragover', e => { e.preventDefault(); zone.classList.add('highlight'); }); zone.addEventListener('dragleave', () => { zone.classList.remove('highlight'); }); zone.addEventListener('drop', e => { e.preventDefault(); zone.classList.remove('highlight'); const draggable = document.querySelector('.dragging'); if (draggable) { // Create a new element instead of moving the original const newElement = draggable.cloneNode(true); newElement.classList.remove('dragging'); newElement.setAttribute('draggable', 'true'); newElement.addEventListener('dragstart', () => { newElement.classList.add('dragging'); }); newElement.addEventListener('dragend', () => { newElement.classList.remove('dragging'); }); zone.appendChild(newElement); } }); }); } // 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(' ')); } }; // Copy code function function copyCode(button) { const codeBlock = button.nextElementSibling; const text = codeBlock.innerText.replace(/\u00a0/g, ' '); navigator.clipboard.writeText(text).then(() => { button.textContent = 'Copied!'; setTimeout(() => { button.textContent = 'Copy'; }, 2000); }); } }); }); </script> 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: Instance vs Class Variables function checkExercise2() { const code = document.getElementById('exercise2-editor').value; const outputElement = document.getElementById('exercise2-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 resetExercise2() { document.getElementById('exercise2-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('exercise2-output').innerHTML = 'Run your code to see output here...'; } // Exercise 3: Creating Methods 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">Perfect! Your method works correctly.\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 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('exercise3-output').innerHTML = 'Run your code to see output here...'; } // Exercise 4: Polymorphism with Shapes 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">Well done! Your polymorphism implementation is correct.\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 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('exercise4-output').innerHTML = 'Run your code to see output here...'; } // Drag and Drop checking functions function checkDragDrop1() { const dropZone = document.getElementById('drop-zone-1'); const outputElement = document.getElementById('drag-output-1'); const children = Array.from(dropZone.children); const code = children.map(child => child.textContent).join('\n'); const expectedOrder = [ 'class Dog:', 'def __init__(self, name, breed):', 'self.name = name', 'self.breed = breed', 'my_dog = Dog("Buddy", "Golden Retriever")', 'print(my_dog.name)' ]; const actualOrder = children.map(child => child.textContent); if (JSON.stringify(actualOrder) === JSON.stringify(expectedOrder)) { outputElement.innerHTML = '<span class="success-message">Correct! The code is in the right order.</span>'; } else { outputElement.innerHTML = '<span class="error-message">Not quite right. Try again!</span>'; } } function resetDragDrop1() { document.getElementById('drop-zone-1').innerHTML = ''; document.getElementById('drag-output-1').innerHTML = 'Arrange the code blocks in the correct order...'; } function checkDragDrop2() { const dropZone = document.getElementById('drop-zone-2'); const outputElement = document.getElementById('drag-output-2'); const children = Array.from(dropZone.children); // Check if the basic structure is correct const hasClass = children.some(child => child.textContent.includes('class BankAccount:')); const hasInit = children.some(child => child.textContent.includes('def __init__')); const hasDeposit = children.some(child => child.textContent.includes('def deposit')); const hasWithdraw = children.some(child => child.textContent.includes('def withdraw')); const hasGetBalance = children.some(child => child.textContent.includes('def get_balance')); if (hasClass && hasInit && hasDeposit && hasWithdraw && hasGetBalance) { outputElement.innerHTML = '<span class="success-message">Good job! The BankAccount class structure is correct.</span>'; } else { outputElement.innerHTML = '<span class="error-message">The class is missing some methods. Try again!</span>'; } } function resetDragDrop2() { document.getElementById('drop-zone-2').innerHTML = ''; document.getElementById('drag-output-2').innerHTML = 'Arrange the code blocks in the correct order...'; } function checkDragDrop3() { const dropZone = document.getElementById('drop-zone-3'); const outputElement = document.getElementById('drag-output-3'); const children = Array.from(dropZone.children); // Check if the inheritance hierarchy is correct const hasAnimalClass = children.some(child => child.textContent.includes('class Animal:')); const hasDogClass = children.some(child => child.textContent.includes('class Dog(Animal):')); const hasCatClass = children.some(child => child.textContent.includes('class Cat(Animal):')); const hasSpeakMethods = children.filter(child => child.textContent.includes('def speak')).length >= 3; if (hasAnimalClass && hasDogClass && hasCatClass && hasSpeakMethods) { outputElement.innerHTML = '<span class="success-message">Excellent! The inheritance hierarchy is correct.</span>'; } else { outputElement.innerHTML = '<span class="error-message">The inheritance structure is not quite right. Try again!</span>'; } } function resetDragDrop3() { document.getElementById('drop-zone-3').innerHTML = ''; document.getElementById('drag-output-3').innerHTML = 'Arrange the code blocks in the correct order...'; } function checkDragDrop4() { const dropZone = document.getElementById('drop-zone-4'); const outputElement = document.getElementById('drag-output-4'); const children = Array.from(dropZone.children); // Check if method overriding is demonstrated correctly const hasVehicleClass = children.some(child => child.textContent.includes('class Vehicle:')); const hasCarClass = children.some(child => child.textContent.includes('class Car(Vehicle):')); const hasStartEngineMethods = children.filter(child => child.textContent.includes('def start_engine')).length >= 2; const hasSuperCall = children.some(child => child.textContent.includes('super().start_engine()')); if (hasVehicleClass && hasCarClass && hasStartEngineMethods && hasSuperCall) { outputElement.innerHTML = '<span class="success-message">Perfect! Method overriding is correctly implemented.</span>'; } else { outputElement.innerHTML = '<span class="error-message">The method overriding example is not complete. Try again!</span>'; } } function resetDragDrop4() { document.getElementById('drop-zone-4').innerHTML = ''; document.getElementById('drag-output-4').innerHTML = 'Arrange the code blocks in the correct order...'; } // Solution functions function showSolution1() { document.getElementById('exercise1-editor').value = `# Sample solution for Exercise 1 class Car: def __init__(self, brand, model, year): self.brand = brand self.model = model self.year = year # Create an instance my_car = Car("Toyota", "Camry", 2020) 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 class Student: school_name = "Tech High" # Class variable def __init__(self, name, grade): self.name = name # Instance variables self.grade = grade # Create instances student1 = Student("Alice", "A") student2 = Student("Bob", "B") # Print data print(f"{student1.name} from {Student.school_name} got grade {student1.grade}") print(f"{student2.name} from {Student.school_name} got grade {student2.grade}")`; } function showSolution3() { document.getElementById('exercise3-editor').value = `# Sample solution for Exercise 3 class Car: def __init__(self, brand, model, year): self.brand = brand self.model = model self.year = year def get_car_age(self): current_year = 2025 return current_year - self.year # Create instance and test method my_car = Car("Toyota", "Camry", 2020) print(f"My car is {my_car.get_car_age()} years old")`; } function showSolution4() { document.getElementById('exercise4-editor').value = `# Sample solution for Exercise 4 import math class Shape: def area(self): return 0 class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2 class Rectangle(Shape): def __init__(self, width, height): self.width = width self.height = height def area(self): return self.width * self.height # Test the implementation circle = Circle(5) rectangle = Rectangle(4, 6) print(f"Circle area: {circle.area():.2f}") print(f"Rectangle area: {rectangle.area()}")`; } </script> </body> </html>