Classes in Python

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:

  • math for math utilities
  • re for regular expressions
  • json to work with JSON
  • datetime to work with dates
  • sqlite3 to use SQLite
  • os for Operating System utilities
  • random for random number generation
  • statistics for statistics utilities
  • requests to perform HTTP network requests
  • http to create HTTP servers
  • urllib to manage URLs

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:

  • Indent using spaces, not tabs
  • Indent using 4 spaces.
  • Python files are encoded in UTF-8
  • Use maximum 80 columns for your code
  • Write each statement on its own line
  • Functions, variable names and file names are lowercase, with underscores between words (snake_case)
  • Class names are capitalized, separate words are written with the capital letter too, (CamelCase)
  • Package names are lowercase and do not have underscores between words
  • Variables that should not change (constants) are written in uppercase
  • Variable names should be meaningful
  • Add useful comments, but avoid obvious comments
  • Add spaces around operators
  • Do not use unnecessary whitespace
  • Add a blank line before a function
  • Add a blank line between methods in a class
  • Inside functions/methods, blank lines can be used to separate related blocks of code to help readability

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.

要查看或添加评论,请登录

Rishav Raj的更多文章

  • The with Statement in Python

    The with Statement in Python

    The statement is very helpful to simplify working with exception handling. For example, when working with files, each…

    2 条评论
  • Variable Scope in Python

    Variable Scope in Python

    When you declare a variable, that variable is visible in parts of your program, depending on where you declare it. If…

  • Functions in Python

    Functions in Python

    A function lets us create a set of instructions that we can run when needed. Functions are essential in Python and in…

  • User Input in Python

    User Input in Python

    In a Python command line application you can display information to the user using the function: We can also accept…

  • Python Basics

    Python Basics

    Variables in Python We can create a new Python variable by assigning a value to a label, using the assignment operator.…

  • Introduction to Python

    Introduction to Python

    Python is literally eating the programming world. It is growing in popularity and usage in ways that are pretty much…

  • Can AI Replace UI/UX Designers: Understanding the Impact of Artificial Intelligence on the Industry

    Can AI Replace UI/UX Designers: Understanding the Impact of Artificial Intelligence on the Industry

    Artificial Intelligence (AI) has come a long way in recent years and has the potential to assist in many fields…

  • Make a simple calculator from python

    Make a simple calculator from python

    # Program make a simple calculator # This function adds two numbers def add(x, y): return x + y # This function…

社区洞察

其他会员也浏览了