Objects


20 min.   |   Advanced  

Classes and Objects

Use class to define a class. Then, create an object (an instance of that class).

The __init__ Method

Use __init__ to initialize an object with data when it’s created.

Attributes

Objects can store data in attributes accessed using dot notation.

Methods

Functions defined inside a class are called methods. They usually take self as the first argument.

Object Identity

Each object is unique and has its own identity in memory.

Class vs. Instance Attributes

Instance attributes belong to one object. Class attributes are shared across all instances.

Inheritance and super()

A child class can inherit from a parent class. Use super() to call the parent’s methods.

Objects: Exercises

Tip Objects: Exercise 1

Create a class Counter() that counts how many numbers in a dataset are above a given threshold. Modify the count_above() method to return the count of all values above the threshold.

Tip Objects: Exercise 2

Create a class Scaler() that multiplies all numbers in a dataset by a scaling factor. Modify the scale() method to return the list of scaled values.

Tip Objects: Exercise 3

Create a class Text() that stores a string and returns the number of words. Modify the word_count() method to return the total count of words.

Tip Objects: Exercise 4

Create a class Text() that stores a string and counts how many times a given character appears. Modify the count_char() method to return the total count of characters.

Tip Objects: Exercise 5

Create a class Text() that stores a string and returns the first word. Modify the first_word() method to return the first word in a string.