CSCI 1100 - Lecture 18

Chapter Thirty-Three Lecture 18 — Classes, Part 1

33.1 Overview

  • Define Types: Create custom data types through classes, allowing developers to model real-world entities and capture the attributes they possess. This capability is fundamental in object-oriented programming.

  • Encapsulate Data: Classes enable the grouping of related data and functions, which helps manage complexity in code. By encapsulating data, you can protect the integrity of your objects and provide a clear interface for interaction.

  • Raise Abstraction Level: Using classes helps to simplify the code by hiding complex implementations. This abstraction allows programmers to focus on higher-level functionality instead of the underlying details.

  • Ease of Writing & Testing: Classes provide a defined structure that makes writing, debugging, and testing code easier. The organization results in cleaner code that is easier to maintain.

  • Code Reusability: Classes promote reusability by defining a blueprint for similar objects. This DRY (Don't Repeat Yourself) principle encourages efficient code management and testing across multiple applications or modules.

33.2 Potential Examples

  • Objects to Consider: Below are types of objects that can be modeled using classes:

    • Date: Can represent day, month, year, and potentially include methods to manipulate date-related functionalities (e.g., adding days).

    • Time: Represents hours, minutes, and seconds, and may offer methods for time calculations.

    • Point: Represents a point in 2D space with x and y coordinates, useful in graphics programming.

    • Rectangle: Could include methods for calculating area, perimeter, or collision detection with other rectangles.

    • Student: Class can encapsulate attributes such as name, student ID, grades, and functions to calculate GPA.

    • Animal: Can model characteristics of different animal species and behaviors.

    • Molecule: Considered for complex biological computations, where different atoms and their bonds are modeled.

  • Data Requirements: It is critical to carefully consider how each object's data will be represented and what functionalities will be needed.

33.3 An Example from Earlier in the Semester

  • Yelp Data Example: Managing restaurant data involves multiple attributes that can complicate the management of data structures. Essential attributes include:

    • Restaurant name

    • Latitude and longitude coordinates to represent location

    • Type of restaurant (e.g., fast food, fine dining)

    • Address of the restaurant

    • Ratings, which may be handled in a separate list or through a specific metrics class.

  • Using Classes: By implementing classes, developers can effectively simplify access to attributes and functions related to each restaurant, enhancing code clarity and reducing redundancy.

33.4 Point2d Class

  • Class Declaration: Begin defining a class with the keyword 'class'. For example, to declare a Point2d class:

    class Point2d(object):
  • Use pass: Initially, pass is used for an empty class to avoid syntax errors and define the structure without functionality.

33.5 Attributes

  • Attributes in Classes: Attributes are variables that hold data specific to each instance of the class. These variables in Python are called attributes, while they might be referred to as member variables in other languages.

  • Defining Attributes: There are several methods for specifying attributes within a class that can be learned progressively.

33.6 Assigning Attributes to Each Instance

  • Example: As an illustration, consider assigning x and y coordinates in a Point2d object:

    from math import sqrt
    p = Point2d()
    p.x = 10
    p.y = 5
    dist_from_origin = sqrt(p.x ** 2 + p.y ** 2)
  • Potential Issues: Some common issues include forgetting to assign attributes or inconsistent naming conventions that can lead to confusion and bugs in larger systems.

33.7 Defining the Attributes Inside the Class

  • Defining Attributes: To initialize attributes directly within the class definition, you can set default values, e.g.,

    class Point2d(object):
        x = 0
        y = 0
  • Initialization: When defined this way, all instances default x and y to 0 unless otherwise specified.

33.8 Defining Attributes Through An Initializer / Constructor

  • Using Initializer: You can utilize an initializer to set x and y when an object is created:

    class Point2d(object):
        def __init__(self, x0, y0):
            self.x = x0
            self.y = y0
  • Default Arguments: This constructor can include default arguments, allowing instance creation without parameters:

    class Point2d(object):
        def __init__(self, x0=0, y0=0):
            self.x = x0
            self.y = y0

33.9 Methods — Functions Associated with the Class

  • Defining Methods: Methods add behavior to the class. For example, you can define a method to calculate the magnitude:

    import math
    class Point2d(object):
        def __init__(self, x0, y0):
            self.x = x0
            self.y = y0
        def magnitude(self):
            return math.sqrt(self.x ** 2 + self.y ** 2)
        def dist(self, o):
            return math.sqrt((self.x - o.x) ** 2 + (self.y - o.y) ** 2)
  • Using Methods: To utilize the methods:

    p = Point2d(0, 4)
    q = Point2d(5, 10)
    leng = q.magnitude()
  • Self Parameter: In method definitions, self refers to the current object, allowing access to the object’s attributes and methods.

33.10 Lecture Exercises, Part 1

  • Exercise Focus: Engage in exercises that extend the functionality of the Point2d class and allow for testing of various methods and attributes defined within it.

33.11 Operators and Other Special Functions

  • Using Operators: Customize how objects of classes interact with one another using operator overloading.

  • Example Operators: Operators such as +, -, *, etc., can be defined for custom behavior.

  • Implementing with Special Functions: For instance, to define addition for Point2d:

    def __add__(self, other):
        return Point2d(self.x + other.x, self.y + other.y)
  • Function Call Representation: Python translates p + q into Point2d.add(p, q). This allows for intuitive use of objects with familiar operators.

33.12 Classes and Modules

  • Module Organization: Each class should ideally have a dedicated module to enhance code clarity, promoting good organization.

  • Best Practice: It is recommended to include tests within the module or within a separate testing module to verify class functionality systematically.

33.13 More Lecture Exercises

  • Next Exercises: Focus on developing additional methods within the class to reinforce understanding and application of class principles in various contexts.

33.14 When to Modify, When to Create New Object

  • Method Behavior Types: Distinguish between methods that modify existing objects (like scale()) and those that create new objects (like operators), which should leave the original object unchanged.

33.15 Programming Conventions

  • Best Practices:

    • Avoid modifying attributes externally; instead, use class methods.

    • Favor design that focuses on methods for behavior rather than direct attribute access.

33.16 Time Example

  • Extended Example: Explore a Time class that could cover varied representation of time, including:

    • Internal representations such as hours/minutes/seconds or total seconds.

    • Inclusion of military time formats or conversions between different time units.

33.17 Summary

  • Key Takeaways:

    • Define new types through classes incorporating both attributes and methods.

    • Use the __init__() constructor to initialize attributes conveniently upon object creation.

    • Utilize special methods to create operators that enable intuitive class object interactions.

    • The chapter reviewed practical examples concerning both the Point2d and Time classes, reinforcing the concepts discussed.