Everything in Python is an object. Every object can contain methods and variables (with unique values). Objects are created (often called instantiated) from classes.
Complete Python Bootcamp: Go from zero to hero in Python 3
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 = ..).
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()