Python Classes
By Flavio Copes
Learn how to define classes in Python and create objects from them, including methods, the self argument, and the __init__ constructor for properties.
In Python we define a class with the class keyword, and from classes we can instantiate objects.
An object is an instance of a class. A class is the type of an object.
Classes let us bundle data and behavior together. Instead of passing around a name and an age as separate variables, we create a Dog object that carries both, plus the things a dog can do.
Defining a class
Define a class in this way:
class <class_name>:
# my class
For example let’s define a Dog class:
class Dog:
# the Dog class
A class can define methods:
class Dog:
# the Dog class
def bark(self):
print('WOF!')
self as the argument of the method points to the current object instance, and must be specified when defining a method.
Forgetting self is a classic mistake. If you write def bark(): and then call roger.bark(), Python raises TypeError: Dog.bark() takes 0 positional arguments but 1 was given. That “1” is the object itself, which Python passes automatically on every method call. The fix is to add self as the first parameter.
Creating an object
We create an instance of a class, an object, using this syntax:
roger = Dog()
Now roger is a new object of type Dog.
If you run
print(type(roger))
You will get <class '__main__.Dog'>
The init() constructor
A special type of method, __init__(), is called constructor. Python calls it automatically when we create a new object, and we can use it to initialize one or more properties:
class Dog:
# the Dog class
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print('WOF!')
We use it in this way:
roger = Dog('Roger', 8)
print(roger.name) # 'Roger'
print(roger.age) # 8
roger.bark() # 'WOF!'
Notice we pass 2 arguments, not 3. self is filled in by Python.
Inside any method, self gives you access to the object’s properties:
def bark(self):
print(f'{self.name} says WOF!')
Now roger.bark() prints Roger says WOF!.
Inheritance
One important feature of classes is inheritance. It lets a class reuse the methods of another class.
We can create an Animal class with a method walk():
class Animal:
def walk(self):
print('Walking..')
and the Dog class can inherit from Animal:
class Dog(Animal):
def bark(self):
print('WOF!')
Now creating a new object of class Dog will have the walk() method, as that’s inherited from Animal:
roger = Dog()
roger.walk() # 'Walking..'
roger.bark() # 'WOF!'
The Animal class knows nothing about dogs. You could add a Cat class inheriting from it too, and both would share walk() without duplicating code.
Related posts about python: