KAHIBARO Bookshelves
Discord Login Register

13.2. Classes and objects

Understanding Classes and Objects in Python

In this chapter, you will connect the idea of object-oriented programming to real Python code. You will learn:

  • What a class looks like in Python
  • How to create (instantiate) objects from a class
  • How to access data and behavior through objects
  • The difference between a class and the objects created from it

This chapter focuses on the Python syntax and usage of classes and objects, not the general theory (which is covered in the parent chapter).


Classes as Blueprints

A class is a blueprint for creating objects.

  • A class describes:
    • What data the objects will have
    • What the objects can do (their behavior)
  • An object (also called an instance) is a concrete thing created from that blueprint.

In Python, a very simple class looks like this:

class Person:
    pass

pass means “do nothing for now”. This is an empty class, but it is still a valid blueprint. You can already create objects from it:

class Person:
    pass
# Create (instantiate) objects
p1 = Person()
p2 = Person()
print(p1)
print(p2)

Each time you write Person(), you create a new object of type Person. Even though the class is empty, p1 and p2 are two different objects.


Creating Objects (Instances)

To create an object from a class, you call the class like a function:

object_name = ClassName()

Example:

class Dog:
    pass
my_dog = Dog()
your_dog = Dog()
print(type(my_dog))   # <class '__main__.Dog'> (in a script)
  • Dog is the class.
  • my_dog is an object (instance) of Dog.
  • type(my_dog) shows the class the object belongs to.

You can create as many objects from a class as you like. They are separate in memory and can usually hold their own data.


Adding Data to Objects After Creation

Even without defining anything inside a class, you can add attributes to individual objects from outside (this is not always good style, but it helps to see how objects work):

class Person:
    pass
p1 = Person()
p2 = Person()
p1.name = "Alice"
p2.name = "Bob"
print(p1.name)  # Alice
print(p2.name)  # Bob

Here:

  • name is an attribute we attach to each object.
  • p1 and p2 each get their own name value.

This is unusual for production code, but it shows an important fact:

Each object can store its own data, even if they come from the same class.

Later chapters (like __init__ and attributes/methods) will show you the proper way to define attributes inside a class.


Class vs Object: Key Differences

Keep these distinctions clear:

  • Class
    • Definition/blueprint.
    • Written once in your code with class ClassName:.
    • Describes what objects could have or do.
    • Example: class Car:
  • Object (Instance)
    • A specific thing created from the class.
    • Created with ClassName().
    • Has actual values stored inside it.
    • Example: my_car = Car()

You can think of it like:

  • Class: a recipe for a cake.
  • Object: an actual cake you can eat.

The `self` Concept in Object Usage

The details of self belong mainly in the __init__ and “Attributes and methods” chapters, but you should see it in basic examples of using objects.

Inside a class, functions that belong to the class usually look like this:

class Dog:
    def bark(self):
        print("Woof!")

When you call this method through an object:

my_dog = Dog()
my_dog.bark()

Python internally turns this into:

Dog.bark(my_dog)

So:

  • my_dog is the object.
  • bark is a method (a function belonging to the class).
  • self is a name we use to refer to “this specific object” inside the class definition.

You rarely call Dog.bark(my_dog) directly; instead you use my_dog.bark(). The important part here is:

Methods are called on objects, and the object itself is passed as the first argument (usually named self).

The detailed explanation of self and attributes is covered in later sections; here you just need to see how methods are used through objects.


Objects and Their Own Data

Even objects from the same class can hold different data. Here’s an example combining class, objects, and simple attributes:

class Cat:
    def speak(self):
        print("Meow!")
# Create two Cat objects
cat1 = Cat()
cat2 = Cat()
# Give them different attributes
cat1.name = "Misty"
cat2.name = "Shadow"
print(cat1.name)  # Misty
print(cat2.name)  # Shadow
cat1.speak()      # Meow!
cat2.speak()      # Meow!
  • Both cat1 and cat2 are Cat objects.
  • They share the same behavior: they both can speak().
  • They can hold different data: cat1.name vs cat2.name.

Later, you will learn how to define attributes like name inside the class itself, so you don’t have to assign them manually from the outside.


The `type()` and `isinstance()` Functions

You can inspect objects to learn about their class.

Using `type()`

type() tells you the class of an object:

class Person:
    pass
p = Person()
n = 42
print(type(p))  # <class '__main__.Person'>  (in a script)
print(type(n))  # <class 'int'>

Using `isinstance()`

isinstance(object, ClassName) checks whether an object is an instance of a particular class:

class Dog:
    pass
d = Dog()
print(isinstance(d, Dog))   # True
print(isinstance(d, int))   # False

This is useful when you want to write code that behaves differently depending on the type of object it receives.


Naming Conventions for Classes and Objects

Following common naming styles makes your code easier to read:

  • Class names: use CamelCase (each word starts with a capital letter, no underscores):
    • Person, BankAccount, ShoppingCart
  • Object (variable) names: use snake_case (lowercase, words separated by underscores):
    • person1, my_account, shopping_cart

Examples:

class BankAccount:
    pass
my_account = BankAccount()
friend_account = BankAccount()

These are conventions, not strict rules, but they are widely used in Python code.


Putting It All Together: A Simple Example

Here is a small, self-contained example showing:

  • Defining a simple class
  • Creating objects
  • Storing data on those objects
  • Calling a method on them
class Person:
    def say_hello(self):
        print("Hello!")
# Create two Person objects
alice = Person()
bob = Person()
# Give them different attributes
alice.name = "Alice"
bob.name = "Bob"
# Use the objects
print(alice.name)   # Alice
alice.say_hello()   # Hello!
print(bob.name)     # Bob
bob.say_hello()     # Hello!

This example keeps the class definition very simple:

  • The class Person defines one behavior: say_hello.
  • The objects alice and bob are created from Person.
  • Each object gets its own name attribute after creation.
  • Both objects can use the say_hello method.

In the next chapters, you will learn how to:

  • Properly define attributes inside the class (with __init__)
  • Separate data (attributes) and behavior (methods) more cleanly
  • Use classes and objects to model more complex, real-world problems.

Views: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Chapter 1: What Is Programming?
    • ☰ 1.1. What is a computer program?
      • ☰ 1.2. What is Python?
        • ☰ 1.3. Where is Python used?
          • ☰ 1.4. How programming helps solve problems
            • ☰ 1.5. Your first Python program
            • ☰ 2. Chapter 2: Setting Up Python
              • ☰ 2.1. Installing Python (Windows / macOS / Linux)
                • ☰ 2.2. Using Python in the terminal
                  • ☰ 2.3. Using an IDE (IDLE / VS Code)
                    • ☰ 2.4. Running Python scripts
                      • ☰ 2.5. Python interactive mode
                      • ☰ 3. Chapter 3: Variables and Data Types
                        • ☰ 3.1. What is a variable?
                          • ☰ 3.2. Creating variables
                            • ☰ 3.3. Numbers
                              • ☰ 3.4. Test
                                • ☰ 3.5. Boolean values
                                  • ☰ 3.6. Type checking
                                  • ☰ 4. Chapter 4: Basic Operations
                                    • ☰ 4.1. Arithmetic operations
                                      • ☰ 4.2. Working with numbers
                                        • ☰ 4.3. String operations
                                          • ☰ 4.4. Combining text and variables
                                            • ☰ 4.5. Comments in Python
                                            • ☰ 5. Chapter 5: User Input and Output
                                              • ☰ 5.1. Getting input from the user
                                                • ☰ 5.2. Converting input to numbers
                                                  • ☰ 5.3. Formatting output
                                                    • ☰ 5.4. Writing interactive programs
                                                    • ☰ 6. Chapter 6: Conditions
                                                      • ☰ 6.1. Comparison operators
                                                        • ☰ 6.2. Logical operators
                                                          • ☰ 6.3. if, elif, else
                                                            • ☰ 6.4. Nested conditions
                                                              • ☰ 6.5. Common beginner mistakes
                                                              • ☰ 7. Chapter 7: Loops
                                                                • ☰ 7.1. Why loops are useful
                                                                  • ☰ 7.2. for loops
                                                                    • ☰ 7.3. while loops
                                                                      • ☰ 7.4. Loop counters
                                                                        • ☰ 7.5. break and continue
                                                                          • ☰ 7.6. Loop exercises
                                                                          • ☰ 8. Chapter 8: Data Collections
                                                                            • ☰ 8.1. Lists
                                                                              • ☰ 8.2. Tuples
                                                                                • ☰ 8.3. Dictionaries
                                                                                  • ☰ 8.4. Sets (basics)
                                                                                    • ☰ 8.5. Choosing the right data structure
                                                                                    • ☰ 9. Chapter 9: Functions
                                                                                      • ☰ 9.1. Why functions matter
                                                                                        • ☰ 9.2. Defining functions
                                                                                          • ☰ 9.3. Parameters and arguments
                                                                                            • ☰ 9.4. Return values
                                                                                              • ☰ 9.5. Scope (local vs global)
                                                                                                • ☰ 9.6. Reusing code
                                                                                                • ☰ 10. Chapter 10: Working with Files
                                                                                                  • ☰ 10.1. What is a file?
                                                                                                    • ☰ 10.2. Reading text files
                                                                                                      • ☰ 10.3. Writing and appending files
                                                                                                        • ☰ 10.4. File paths
                                                                                                          • ☰ 10.5. Simple file-based programs
                                                                                                          • ☰ 11. Chapter 11: Errors and Debugging
                                                                                                            • ☰ 11.1. Types of errors
                                                                                                              • ☰ 11.2. Reading error messages
                                                                                                                • ☰ 11.3. Common beginner errors
                                                                                                                  • ☰ 11.4. try and except
                                                                                                                    • ☰ 11.5. Debugging strategies
                                                                                                                    • ☰ 12. Chapter 12: Using Python Libraries
                                                                                                                      • ☰ 12.1. What is a library?
                                                                                                                        • ☰ 12.2. Importing modules
                                                                                                                          • ☰ 12.3. Standard libraries
                                                                                                                            • ☰ 12.3.1. math
                                                                                                                              • ☰ 12.3.2. random
                                                                                                                                • ☰ 12.3.3. datetime
                                                                                                                                • ☰ 12.4. Installing external libraries with pip
                                                                                                                                • ☰ 13. Chapter 13: Object-Oriented Programming
                                                                                                                                  • ☰ 13.1. What is object-oriented programming?
                                                                                                                                    • ☰ 13.2. Classes and objects
                                                                                                                                      • ☰ 13.3. The `__init__` method
                                                                                                                                        • ☰ 13.4. Attributes and methods
                                                                                                                                          • ☰ 13.5. Encapsulation
                                                                                                                                            • ☰ 13.6. Inheritance (basics)
                                                                                                                                              • ☰ 13.7. Simple OOP examples
                                                                                                                                              • ☰ 14. Chapter 14: Automation with Python
                                                                                                                                                • ☰ 14.1. What is automation?
                                                                                                                                                  • ☰ 14.2. Automating simple tasks
                                                                                                                                                    • ☰ 14.3. Working with files and folders
                                                                                                                                                      • ☰ 14.4. Automating text processing
                                                                                                                                                        • ☰ 14.5. Scheduling scripts
                                                                                                                                                          • ☰ 14.6. Practical automation examples
                                                                                                                                                          • ☰ 15. Chapter 15: Web Development with Python
                                                                                                                                                            • ☰ 15.1. How the web works (basic overview)
                                                                                                                                                              • ☰ 15.2. Introduction to Flask
                                                                                                                                                                • ☰ 15.3. Creating a simple web server
                                                                                                                                                                  • ☰ 15.4. Routing and templates
                                                                                                                                                                    • ☰ 15.5. Handling user input (forms)
                                                                                                                                                                      • ☰ 15.6. Very basic APIs
                                                                                                                                                                      • ☰ 16. Chapter 16: Data Science with Python
                                                                                                                                                                        • ☰ 16.1. What is data science?
                                                                                                                                                                          • ☰ 16.2. Working with data
                                                                                                                                                                            • ☰ 16.3. Introduction to NumPy
                                                                                                                                                                              • ☰ 16.4. Introduction to pandas
                                                                                                                                                                                • ☰ 16.5. Data visualization with matplotlib
                                                                                                                                                                                  • ☰ 16.6. Simple data analysis examples
                                                                                                                                                                                  • ☰ 17. Chapter 17: Mini Projects
                                                                                                                                                                                    • ☰ 17.1. Number guessing game
                                                                                                                                                                                      • ☰ 17.2. Simple calculator
                                                                                                                                                                                        • ☰ 17.3. To-do list
                                                                                                                                                                                          • ☰ 17.4. Password generator
                                                                                                                                                                                            • ☰ 17.5. Quiz application
                                                                                                                                                                                              • ☰ 17.6. Small web or data project
                                                                                                                                                                                              • ☰ 18. Chapter 18: Next Steps
                                                                                                                                                                                                • ☰ 18.1. How to practice Python
                                                                                                                                                                                                  • ☰ 18.2. Writing clean and readable code
                                                                                                                                                                                                    • ☰ 18.3. Choosing a specialization
                                                                                                                                                                                                      • ☰ 18.3.1. Web development
                                                                                                                                                                                                        • ☰ 18.3.2. Data science
                                                                                                                                                                                                          • ☰ 18.3.3. Automation
                                                                                                                                                                                                            • ☰ 18.3.4. Software development
                                                                                                                                                                                                            • ☰ 18.4. Learning resources and communities
                                                                                                                                                                                                            • ☰ 19. Appendix
                                                                                                                                                                                                              • ☰ 19.1. Python syntax cheat sheet
                                                                                                                                                                                                                • ☰ 19.2. Common errors and solutions
                                                                                                                                                                                                                  • ☰ 19.3. Glossary of terms