Table of Contents
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)Dogis the class.my_dogis an object (instance) ofDog.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) # BobHere:
nameis an attribute we attach to each object.p1andp2each get their ownnamevalue.
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_dogis the object.barkis a method (a function belonging to the class).selfis 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
cat1andcat2areCatobjects. - They share the same behavior: they both can
speak(). - They can hold different data:
cat1.namevscat2.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)) # FalseThis 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
Persondefines one behavior:say_hello. - The objects
aliceandbobare created fromPerson. - Each object gets its own
nameattribute after creation. - Both objects can use the
say_hellomethod.
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.