classEasy Examples

Defines a new class (blueprint for creating objects)

Define a simple class

Creating a class with attributes and a method.

python
class Dog:
    def __init__(self, name, breed):
        self.name = name
        self.breed = breed

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

dog = Dog("Rex", "Labrador")
print(dog.bark())
print(dog.name)
print(dog.breed)
Expected Output
Rex says Woof!
Rex
Labrador

A class bundles data (attributes) and behavior (methods) together. __init__ runs when you create a new instance.

Class with default values

Using default arguments in __init__.

python
class Counter:
    def __init__(self, start=0):
        self.count = start

    def increment(self):
        self.count += 1

    def get(self):
        return self.count

c = Counter()
c.increment()
c.increment()
c.increment()
print(c.get())

c2 = Counter(100)
c2.increment()
print(c2.get())
Expected Output
3
101

Default parameter values let you create objects without specifying every argument.

Want to try these examples interactively?

Open Easy Playground