Classes & Objects

A class is a blueprint; objects are instances made from it.

Syntaxclass Name: ...

A class is a blueprint for creating objects. An object (or instance) is a specific thing built from that blueprint, with its own data.

Making objects

Define a class with the class keyword, then call it like a function to create an instance.

One class acts as a blueprint for many object instancesclass DogblueprintDog('Rex', 3)Dog('Fido', 5)Dog('Bella', 2)objects (instances)
The class is the blueprint; each object is a separate instance with its own data.

Example

Example · python
class Dog:
    pass

rex = Dog()
fido = Dog()
print(type(rex))
print(rex is fido)

# Output:
# <class '__main__.Dog'>
# False

When to use it

  • A banking app models an Account as a class with balance and transaction methods.
  • A game defines an Enemy class to share behaviour across multiple monster types.
  • A REST API serialiser maps each resource type (User, Product, Order) to its own class.

More examples

Define a simple class

Defines a class with a class-level attribute and an instance method, then creates an object.

Example · python
class Dog:
    species = 'Canis lupus familiaris'

    def bark(self):
        print('Woof!')

fido = Dog()
fido.bark()             # Woof!
print(Dog.species)      # Canis lupus familiaris

Multiple instances share methods

Shows that two instances share the same method but each has its own independent state.

Example · python
class Counter:
    def increment(self):
        self.value = getattr(self, 'value', 0) + 1

a = Counter()
b = Counter()
a.increment()
a.increment()
b.increment()
print(a.value, b.value)   # 2 1

Class with class and instance attribute

Contrasts a shared class attribute (tax_rate) with per-instance attributes (name, price).

Example · python
class Product:
    tax_rate = 0.10   # class attribute shared by all

    def __init__(self, name, price):
        self.name = name    # instance attribute
        self.price = price

p = Product('Book', 20)
print(p.name, p.price * (1 + Product.tax_rate))
# Output: Book 22.0

Discussion

  • Be the first to comment on this lesson.