Python Module 5 - Summary Answers
1. Class, Object, Attributes, and copy.copy():
- Class: Blueprint for objects.
- Object: Instance of class.
- Attributes: Data stored in objects.
Example:
import copy
class Point: pass
p1 = Point(); p1.x = 3.0; p1.y = 4.0
p2 = copy.copy(p1) # Shallow copy
2. Pure Functions and Modifiers:
- Pure function: Returns new data, does not change original.
- Modifier: Changes original data.
Example: add_time() vs increment()
3. Current Date and Day:
import datetime
print(datetime.datetime.now().strftime("%A"))
4. Operator Overloading & Polymorphism:
- Overloading: Define __add__ method.
- Polymorphism: One function, different types.
Example: histogram("banana"), histogram([1,2,2])
5. Inheritance & Class Diagrams:
class A: pass
class B(A): pass # IS-A
Class diagram shows IS-A and HAS-A relationships.
6. print_time Function:
class Time:
def print_time(self): print(f"{self.hour}:{self.minute}:{self.second}")
7. Define & Instantiate Class:
class Person:
def __init__(self, name): self.name = name
p = Person("Alice"); print(p.name)
8. Class vs Instance Variables:
- Class: Shared. Instance: Unique.
class A:
x = 5 # class var
def __init__(self): self.y = 10 # instance var
9. Birthday Age Calculator:
class Person:
def __init__(self, bday): ...
def age_details(self): ...
10. Point Midpoint & reflex_x:
class Point:
def midpoint(self, other): ...
def reflex_x(self): ...
11. Student Details with Inheritance:
class Person, MarksAttendance, Student...
Student("1AB16CS005", "XYZ", ...).display()
12. RECTANGLE Class Example:
class Rectangle:
def center(self): ...
def area(self): ...
def perimeter(self): ...
13. __init__ and __str__:
class Time:
def __init__(): ...
def __str__(): return "...formatted..."
14. Polymorphism and Histogram:
def histogram(s): counts chars or list items