Week 6: Object-Oriented Programming
CarFactory
is the class. It defines that all cars will have a color and a model. Each individual Car
that rolls off the assembly line is an object with its own specific color and model.__init__
method__init__
method is a special function called a constructor. It runs automatically whenever a new object is created.self
parameter is a reference to the specific instance of the class being created. We use it to attach data to the object.class Student:
"""Represents a student in a course."""
def __init__(self, name: str, student_id: int):
# These are attributes of the Student object
self.name = name
self.student_id = student_id
self.is_enrolled = True
# Create two instances (objects) of the Student class
student_one = Student("Grace Hopper", 1001)
student_two = Student("Ada Lovelace", 1002)
__str__
method__str__
method is another special “dunder” (double underscore) method.print(my_object)
, python automatically calls this method behind the scenes.class Student:
"""Represents a student in a course."""
def __init__(self, name: str, student_id: int):
self.name = name
self.student_id = student_id
def __str__(self) -> str:
"""Returns a string representation of the student."""
return f"Student Name: {self.name}, ID: {self.student_id}"
student_one = Student("Grace Hopper", 1001)
print(student_one)
Book
, Movie
, or Product
.__init__
method to store its attributes, and a descriptive __str__
method.__init__
, methods must always have self
as their first parameter, allowing them to access and modify the object’s own attributes.Car
, Truck
, and Motorcycle
could all inherit from a parent Vehicle
class.class ChildClass(ParentClass):
to define an inheritance relationship.__init__
method, we must call super().__init__(...)
to make sure the parent class’s constructor is also run.labs/lab06/README.md
.IS4010: App Development with AI