PythonMastery

Create a class in Python

A simple Python class with __init__, attributes and methods. Create two objects from it and see that each one keeps its own data.

A class is a template for making objects. Each object made from the class (an instance) has its own data, called attributes, and shares the functions defined in the class, called methods.

The program

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

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

    def learn(self, trick):
        self.tricks.append(trick)


rex = Dog("Rex", "Labrador")
bella = Dog("Bella", "Beagle")

rex.learn("sit")
rex.learn("roll over")

print(rex.bark())
print(f"{rex.name} the {rex.breed} knows: {rex.tricks}")
print(f"{bella.name} the {bella.breed} knows: {bella.tricks}")
output
Rex says: Woof!
Rex the Labrador knows: ['sit', 'roll over']
Bella the Beagle knows: []

How it works

A readable print

Printing the object itself gives a default text such as <__main__.Dog object at 0x7f...>. Add a __repr__ method to choose what is shown:

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

    def __repr__(self):
        return f"Dog({self.name!r}, {self.breed!r})"


print(Dog("Rex", "Labrador"))
output
Dog('Rex', 'Labrador')

Learn the idea: Object-Oriented Programming