Concepts / Creating Your First Python Class

Creating Your First Python Class

The class describes the common structure.

  • Programming

From Plan to Object

Imagine designing a system for bank accounts. Each account needs information such as an account number, an owner's name, and a balance. It also needs actions such as depositing, withdrawing, and checking the balance. You could keep these pieces as separate variables and functions, but they would be scattered across the program. A class gives you a way to organize the related information and actions together.

A class is a blueprint. It describes the data an object will hold and the actions it can perform. An object is an instance created from that blueprint. Multiple objects can come from one class, and each object can have its own values while following the same overall plan.

BankAccount classaccount number, owner,balance; deposit, withdraw,check balanceAccount object 1balance: 500Account object 2balance: 2000createscreates
How does one class blueprint become separate objects with their own data?

Data and Behavior Together

An object bundles data and behavior into one organized unit. The data is represented by attributes. The behavior is represented by methods. This bundling means that instead of juggling unrelated variables and functions, you work with one self-contained object.

Definition

An attribute is a piece of data that belongs to an object. It stores information about the object's state or characteristics. For a Student object, possible attributes include name, student_id, and gpa. Each student object has its own values for those attributes.

Definition

A method is a function that lives inside an object. While an attribute stores data, a method performs an action. Methods typically work with the object's attributes. A Student object might have a calculate_letter_grade method that uses gpa, or an update_gpa method that changes the gpa attribute.

Student objectnamea student's namecalculate_letter_gradeuses gpastudent_ida student's identifierupdate_gpachanges gpagpaa student's gpacontainscontainscontainscontainscontainsuseschanges
What data does an object contain, and how does its behavior relate to that data?

The important distinction is data versus action. A balance is information about a bank account, so it is an attribute. Depositing money is something the account can do, so it is represented by a method. A method can use an attribute or change an attribute as part of its action.

The Class Structure

The class keyword tells Python that a blueprint is beginning. It is followed by a class name, a colon, and an indented block. Inside that indented block, the class groups the attributes and methods that belong to objects created from it.

python

The organizational benefit is practical. When you need to understand or extend a bank account, the related data and behavior are in the BankAccount class. This makes code easier to understand, easier to maintain, easier to debug, and easier to reuse.

Writing and Running Code

Before a class can help you organize a program, you need to know where Python code is written and how it runs. In this course, you write Python in a built-in editor in your browser. You do not need to install Python on your computer. The editor is connected to a Python interpreter.

Course editorPython textRun actionbutton or automaticexecutionPython interpreterreads and executesinstructionsOutput areatext, numbers, or errorscode waitsstartsdisplays result
How does code move from the course editor to the result on the screen?

Writing code and running code are separate actions. When you type a statement into the editor, it is only written code. It has not produced a result yet. When you run the code, the interpreter reads it, executes the instructions, and displays the result in the output area.

python
Output
Hello, World!

This statement uses the built-in print function to display text. The parentheses contain the value given to print, and the quotation marks identify Hello, World! as a string. When you run the statement, the interpreter recognizes print as a function call and the text appears in the output area.

A Complete First Run

Worked example

Tracing the first statement

What happens when you enter print("Hello, World!") in the course editor and run it?

  1. 1
    Write

    You type the Python statement into the editor. At this point, the code is present but has not produced output.

  2. 2
    Run

    You press the run button, or the course environment triggers execution.

  3. 3
    Read

    The Python interpreter reads the statement and recognizes print as a function.

  4. 4
    Execute

    The interpreter executes print with the string Hello, World! as its input.

  5. 5
    Display

    The print function displays the string in the output area.

Result

The output area shows Hello, World!

This small run demonstrates the same general cycle you will use while learning classes: write instructions, run them, inspect the result, and revise the code when necessary. A class organizes related data and behavior, while the interpreter executes the Python statements you write.

python
Output
42
3.14
15

Python executes statements sequentially from top to bottom. The first statement prints 42, the second prints 3.14, and the third evaluates 10 + 5 before printing 15. The string "42" and the number 42 may look similar when displayed, but Python treats text and numbers as different kinds of values.

Mistakes to Catch Early

  • Common mistake

    Treating a class and an object as the same thing

    What it looks like

    Calling the BankAccount blueprint one particular bank account

    Why it fails

    A class is the blueprint, while an object is an instance created from that blueprint.

    Do this instead

    Use the class to describe the common structure and use objects to represent separate accounts with their own attribute values.

  • Common mistake

    Confusing attributes with methods

    What it looks like

    Calling balance an action or calling deposit stored information

    Why it fails

    Attributes store information. Methods perform actions.

    Do this instead

    Classify account number, owner name, and balance as attributes; classify deposit, withdraw, and check balance as methods.

  • Common mistake

    Expecting written code to produce output immediately

    What it looks like

    Typing print("Hello") and waiting without running the code

    Why it fails

    Writing and running are separate actions. The interpreter reads the code only when execution is triggered.

    Do this instead

    Run the code after writing it, then inspect the output area.

  • Common mistake

    Treating text and numbers as identical values

    What it looks like

    Assuming the string "42" and the number 42 are the same to Python

    Why it fails

    Quotation marks identify text as a string, while an unquoted number is treated as a number.

    Do this instead

    Use quotation marks for text and remember that Python treats strings and numbers differently.

  • Common mistake

    Scattering related data and actions instead of grouping them

    What it looks like

    Keeping account information in separate variables and account actions in unrelated functions

    Why it fails

    The related pieces become harder to understand, maintain, debug, and reuse.

    Do this instead

    Use a class to group related attributes and methods into a coherent unit.

Your Turn in the Editor

EASY

Run a Python statement in the course editor that displays your own short greeting. Then change the text and run it again. Before each run, identify whether you are currently writing code or running code. Finally, describe which parts of the BankAccount design would be attributes and which would be methods.

Hints
  • Use the print function with parentheses.
  • Put the greeting inside quotation marks because it is text.
  • For the account design, ask whether each item stores information or performs an action.
EASY

Classify each item in this bank account model as a class, object, attribute, or method: BankAccount, one account with a balance of 500 dollars, balance, and deposit.

Hints
  • The class is the blueprint.
  • The object is one individual instance.
  • An attribute stores information.
  • A method performs an action.

What to Remember

  1. 1
    A class is a blueprint, and an object is an instance created from that blueprint.
  2. 2
    Attributes store an object's information, while methods perform actions involving that object's data.
  3. 3
    The class keyword begins a blueprint and groups related attributes and methods into one organized unit.
  4. 4
    In this course, you write Python in the browser-based editor and run it through the connected Python interpreter.
  5. 5
    Writing code places instructions in the editor; running code causes the interpreter to execute them and display output or an error.

At a glance

  • A class provides the plan for an object, while each object is a separate instance with its own data.
  • Attributes represent stored information such as a student's name or a bank account's balance.
  • Methods represent actions such as depositing money or updating a student's gpa.
  • The class keyword groups related data and behavior so the program is easier to understand, maintain, and reuse.
  • Python code becomes visible output only after the course interpreter reads and executes it.

Related concepts

More concepts starting with C