Classes in Python
In addition to using the Python-provided types, we can declare our own classes, and from classes we can instantiate objects.
An object is an instance of a class. A class is the type of an object.
We can 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.
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'>
A special type of method, __init__() is called constructor, and we can use it to initialize one or more properties when we create a new object from that class:
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!'
One important feature of classes is inheritance.
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!'
Modules in Python
Every Python file is a module.
You can import a module from other files, and that's the base of any program of moderate complexity, as it promotes a sensible organization and code reuse.
In the typical Python program, one file acts as the entry point. The other files are modules and expose functions that we can call from other files.
The file dog.py contains this code:
def bark():
print('WOF!')
We can import this function from another file using import. And once we do, we can reference the function using the dot notation, dog.bark():
import dog
dog.bark()
Or, we can use the from .. import syntax and call the function directly:
from dog import bark
bark()
The first strategy allows us to load everything defined in a file.
The second strategy lets us pick the things we need.
Those modules are specific to your program, and importing depends on the location of the file in the filesystem.
Suppose you put dog.py in a lib subfolder.
领英推荐
In that folder, you need to create an empty file named __init__.py. This tells Python the folder contains modules.
Now you can choose - you can import dog from lib:
from lib import dog
dog.bark()
or you can reference the dog module specific function importing from lib.dog:
from lib.dog import bark
bark()
The Python Standard Library
Python exposes a lot of built-in functionality through its standard library.
The standard library is a huge collection of all sort of utilities, ranging from math utilities to debugging to creating graphical user interfaces.
You can find the full list of standard library modules here: https://docs.python.org/3/library/index.html
Some of the important modules are:
Let's introduce how to use a module of the standard library. You already know how to use modules you create, importing from other files in the program folder.
Well that's the same with modules provided by the standard library:
import math
math.sqrt(4) # 2.0
or
from math import sqrt
sqrt(4) # 2.0
We'll soon explore the most important modules individually to understand what we can do with them.
The PEP8 Python Style Guide
When you write code, you should adhere to the conventions of the programming language you use.
If you learn the right naming and formatting conventions right from the start, it will be easier to read code written by other people, and people will find your code easier to read.
Python defines its conventions in the PEP8 style guide. PEP stands for Python Enhancement Proposals and it's the place where all Python language enhancements and discussions happen.
There are a lot of PEP proposals, all available at https://www.python.org/dev/peps/.
PEP8 is one of the first ones, and one of the most important, too. It defines the formatting and also some rules on how to write Python in a "pythonic" way.
You can read its full content here: https://www.python.org/dev/peps/pep-0008/ but here's a quick summary of the important points you can start with:
Debugging in Python
Debugging is one of the best skills you can learn, as it will help you in many difficult situations.
Every language has its debugger. Python has pdb, available through the standard library.
You debug by adding one breakpoint into your code:
breakpoint()
You can add more breakpoints if needed.
When the Python interpreter hits a breakpoint in your code, it will stop, and it will tell you what is the next instruction it will run.
Then and you can do a few things.
You can type the name of any variable to inspect its value.
You can press n to step to the next line in the current function. If the code calls functions, the debugger does not get into them, and considers them "black boxes".
You can press s to step to the next line in the current function. If the next line is a function, the debugger goes into that, and you can then run one instruction of that function at a time.
You can press c to continue the execution of the program normally, without the need to do it step-by-step.
You can press q to stop the execution of the program.
Debugging is useful to evaluate the result of an instruction, and it's especially good to know how to use it when you have complex iterations or algorithms that you want to fix.