SyntaxStudy
Sign Up
Python Beginner 8 min read

Classes & Objects

Classes & Objects

A class is a blueprint for creating objects. An object is an instance of a class with its own data (attributes) and behavior (methods).

Defining a Class

class Dog:
    """A simple Dog class."""

    def __init__(self, name, breed, age):
        """Constructor — called when Dog() is invoked."""
        self.name  = name    # instance attribute
        self.breed = breed
        self.age   = age

    def bark(self):
        return f"{self.name} says: Woof!"

    def birthday(self):
        self.age += 1
        return f"{self.name} is now {self.age} years old."

Creating Instances

fido  = Dog("Fido",  "Labrador", 3)
bella = Dog("Bella", "Poodle",   5)

print(fido.name)        # Fido
print(bella.bark())     # Bella says: Woof!
print(fido.birthday())  # Fido is now 4 years old.

Accessing Attributes

print(vars(fido))           # {'name': 'Fido', ...}
print(hasattr(fido, "age")) # True
setattr(fido, "color", "golden")
print(fido.color)           # golden
Example
class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

    def perimeter(self):
        return 2 * (self.width + self.height)

    def is_square(self):
        return self.width == self.height

r = Rectangle(4, 6)
print(f"Area: {r.area()}")
print(f"Perimeter: {r.perimeter()}")
print(f"Is square: {r.is_square()}")
Pro Tip

self is just a convention — you could name it anything — but stick to self. It refers to the specific instance on which the method is being called.