Classes and Objects
- As programs get larger, it can become challenging to organize our code and keep track of all the parts/functions.
- Modules do help, but it is an incomplete solution.
- A second key component is being able to bundle data into one single object.
- For example a single variable called
date
instead of managing separatemonth
,day
, andyear
variables. - Named tuples help with this.
- For example a single variable called
- Object-oriented programming combines these two ideas, and is currently the dominant technique used for organizing code.
- We interact with the word in terms of objects: table, chair, car, person, stove, etc.
- When thinking about an object, we consider two main things:
- It’s properties
- How we can interact with it.
- A car may have properties like
- number of seats,
- engine size/type
- number of doors
- color
- We interact with a car using the steering wheel and pedals (among other things).
- All variables refer to some object.
- Some objects have very simply properties:
i = 17
is “just” a number
- Most objects naturally have many properties.
- A Date has a month, day and year.
- Objects have a set of actions that let us interact with them.
ordinal_date
days_elapsed
etc.
-
A class is a blueprint that describes what properties an object has and what actions can be performed on it.
-
This says that an object that is a
Date
has year, month, and day as a property.class Date: """ A class that represents a date """ def __init__(self): self.year = 0 self.month = 0 self.day = 0
-
This says that an object that is a
Time
has a hour and a minute.class Time: """ A class that represents a time of day """ def __init__(self): self.hours = 0 self.minutes = 0
date1 = Date() date1.year = 2022 date1.month = 11 date1.day = 4 print(f"date1 is {date1.year}-{date1.month}-{date1.day}") date2 = Date() date2.year = 2024 date2.month = 7 date2.day = 4
- Notice above that
date1
anddate2
are different objects. (Just like these are different pens/desks, etc.). - Each object has different values for it’s properties.
- But, since
date1
anddate2
are members of the same class, they have the same set of properties (month, day, year) - In some sense, a class is a “blueprint” that tells how to construct an object.
Methods
-
instance methods are functions defined within a class. They provide the means for interacting with an object.
def make_string(self): return f"{self.year}-{self.month}-{self.day}" print(date1.make_string())
def increment_minute(self): self.minute += 1 if (self.minute >= 60): self.hour += 1
Next steps
- Constructor
- class variables
- encapsulation / information hiding.
- alarm clock example
- separate interface from implementation
- put underscore in front of “private” methods.
- Avoid accessing instance variables directly.
- “Perl doesn’t have an infatuation with enforced privacy. It would prefer that you stayed out of its living room because you weren’t invited, not because it has a shotgun”