python logo

python class tutorial


Python hosting: Host, run, and code Python in the cloud!

Everything in Python is an object. Every object can contain methods and variables (with unique values). Objects are created (often called instantiated) from classes.

Related courses
Python Programming Bootcamp: Go from zero to hero

Class example
Consider the example below:


class Animal:
def __init__(self,name):
self.name = name

def walk(self):
print(self.name + ' walks.')

duck = Animal('Duck')
duck.walk()

We create one object called ‘duck’ from the class Animal. The class has a method (walk) that can be called on each object. We also have a method called init(), this is a method that is always called when a new object is created. The self keyword is required for every method. We set the variables with the class (self.name = ..).

python class Python class and object drawn using the modeling language UML

Once the object is created, we can call its methods and use its variables indefinitely. Every object of the same class has the same methods, but its variables contents may differ.

A Python program may consists of many classes and objects. To demonstrate that, we create two objects from one class:


class Animal:
def __init__(self,name):
self.name = name

def walk(self):
print(self.name + ' walks.')

duck = Animal('Duck')
duck.walk()

rhino = Animal('African Rhino')
rhino.walk()

If you are new to Python programming, I highly recommend this book.

Download Exercises

BackNext





Leave a Reply: