from sklearn.linear_model import LogisticRegression
dir(LogisticRegression)
Classes & Exceptions
Classes
Classes are central elements in Object-oriented programming (OOP)
A class structure defines an object, its properties, and all the operations one can apply to it. Moreover, it allows the creation of multiple instances of the same object, each with its own properties, and to apply the same operations to all of them. Another key concept is the one of inheritance, defining a new class from an existing one by simply inheriting all its properties and operations.
In Python, a class contains attributes (variables) and methods (functions). Syntactically, it is defined similarly to a function, replacing the def
keyword with class
and requiring a colon :
at the end of the first line. The name of a class should be CamelCase1 (or CapWords).
1 CamelCase (🇫🇷: casse de chameau): the name comes from the “bumpy” look of its letters as in the Wikipedia illustration below
For instance, in sklearn
, the Logistic Regression class is named LogisticRegression
, and can be loaded and investigated as follows:
['__annotations__',
'__class__',
'__delattr__',
'__dict__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getstate__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__le__',
'__lt__',
'__module__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__setattr__',
'__setstate__',
'__sizeof__',
'__sklearn_clone__',
'__str__',
'__subclasshook__',
'__weakref__',
'_build_request_for_signature',
'_check_feature_names',
'_check_n_features',
'_doc_link_module',
'_doc_link_template',
'_doc_link_url_param_generator',
'_estimator_type',
'_get_default_requests',
'_get_doc_link',
'_get_metadata_request',
'_get_param_names',
'_get_tags',
'_more_tags',
'_parameter_constraints',
'_predict_proba_lr',
'_repr_html_',
'_repr_html_inner',
'_repr_mimebundle_',
'_validate_data',
'_validate_params',
'decision_function',
'densify',
'fit',
'get_metadata_routing',
'get_params',
'predict',
'predict_log_proba',
'predict_proba',
'score',
'set_fit_request',
'set_params',
'set_score_request',
'sparsify']
In particular, you can already discover the attributes and methods shared to all classes (e.g., __class__
, __init__
, __doc__
,), and the one specific to the LogisticRegression
class (e.g., fit
, get_params
, predict
, etc.).
Usually, a class contains some class methods that can be seen as functions inside the class.
The first argument of a (non-static) method is usually called
self
: it is a mandatory element. Thisself
argument is for self-reference. Self is a convention and not a Python keyword, so any other name can be used instead ofself
(e.g.,this
orme
orin_place_of_self
).Some method names have a specific meaning, for instance:
__init__
: name of the method invoked when creating the object (instantiation)__call__
: method invoked when calling the object__str__
: method invoked when a class has a representation as a string, e.g., when passing it to theprint
function- see Python documentation for more special names.
A first example
Let us define a simple Point
class, representing a point in the plane (i.e., a point in \mathbb{R}^2):
class Point(object):
"""A class to represent planar points."""
def __init__(self, x, y):
"""Create a new point (x, y)."""
self.x = x
self.y = y
def translate(self, dx, dy):
"""Translate the point by dx and dy."""
self.x += dx
self.y += dy
def __str__(self):
return f"Point: [{self.x:.3f}, {self.y:.3f}]"
If you are not familiar with printing in Python, start with the new f-strings format; see for instance: https://zetcode.com/python/fstring/.
To create a new instance of the class Point
you run the following code:
= Point(x=0, y=0) # call __init__ ; p1
Now, you can access the attributes of the object p1
:
print(p1.x, p1.y)
print(f"{p1}") # call __str__
print(p1)
print(p1.__doc__)
0 0
Point: [0.000, 0.000]
Point: [0.000, 0.000]
A class to represent planar points.
To apply our translate
method to the point p1
:
=1, dy=1)
p1.translate(dxprint(p1.translate)
print(p1)
print(type(p1))
<bound method Point.translate of <__main__.Point object at 0x77a9985f8740>>
Point: [1.000, 1.000]
<class '__main__.Point'>
Implicitly, the previous command is equivalent to Point.translate(p1, dx=1, dy=1)
. Indeed, you can check the output of the following command:
= Point(x=0, y=0)
p1 =1, dy=1)
Point.translate(p1, dxprint(p1)
Point: [1.000, 1.000]
You might have already used that syntax with the “dot” (.
) notation in numpy
, for instance when executing a numpy
function as follows
import numpy as np
= np.random.default_rng(seed=12345)
rng = rng.random((3, 3))
a =0) a.mean(axis
array([0.50063315, 0.29820069, 0.60097848])
In that case, a
was an instance of the numpy.ndarray
class (see numpy documentation for details on this class):
type(a)
numpy.ndarray
Built-in method: __call__
MyClass(arg1, arg2, ...)
is a shorthand for MyClass.__call__(arg1, arg2, ...)
, so this allows writing classes where the instances behave like functions and can be called like a function
class Sum:
def __init__(self):
print("Instance Created")
# Defining __call__ method
def __call__(self, a, b):
print(a + b)
# Instance created
= Sum()
sum_as_a_function
# __call__ method will be called
10, 20) sum_as_a_function(
Instance Created
30
A test function of interest is isinstance
which allows checking if an object is of the correct class. For instance, one can check if sum_as_a_function
is an instance of Sum
isinstance(sum_as_a_function, Sum)
True
or an instance of Point
:
isinstance(sum_as_a_function, Point)
False
Another example of a callable is given below with a simple Counter
class:
class Counter:
"""A simple counter class."""
def __init__(self):
self.count = 0
def increment(self):
self.count += 1
def __call__(self):
self.increment()
Then, performing the following commands you can check how the __call__
method is called:
= Counter()
counter print(counter.count)
counter.increment()print(counter.count)
counter()print(counter.count)
0
1
2
In particular, note that a method of a class can modify the state of a particular instance. This does not alter the other instantiations of the class.
This example and more details on callable are described in detail in this Real Python post.
An operator like +
may have a different meaning depending on the context (e.g., addition of numbers, concatenation of strings, etc.). This is called operator overloading, or sometimes ad hoc polymorphism.
Inheritance
Classes can inherit methods from other classes. You can use super
(Latin word for “above”) to access the parent class from a child class. This is useful when you want to extend the functionality of the inherited method.
A simple test consists of checking whether a class has inherited from another one. issubclass
allows one to check this heritage property. For instance, we can check that the following IsoGaussian
is a subclass of the Gaussian
class we have created above:
class IsoGaussian(Gaussian):
def __init__(self, mean):
super().__init__(mean, 1.0)
= IsoGaussian(3)
gg1 print(gg1)
print(issubclass(IsoGaussian, Gaussian))
pdf: exp(-(x - 3.000)^2 / (1.000*2^2)) / sqrt(2 * pi * 1.000^2)
True
For more information on super
, see for instance this Real Python Tutorials.
Many other examples can be found in the scikit-learn
package (see for instance the module Linear Model often used in machine learning or statistics).
Exceptions
This section is inspired by Fabien Maussion’s lecture on Scientific Programming, and describes how to handle exceptions in python
.
- In
python
errors are handled throughExceptions
- An error throws an
Exception
interrupting the normal code execution - Execution can overpass such an issue inside a bloc with
try
-except
- A typical use case: stop the program when an error occurs:
def my_function(arguments):
if not verify(arguments):
raise Exception("Invalid arguments")
# ...
# Keep working if the exception is not raised
The list of possible errors is available here: https://docs.python.org/3/library/exceptions.html#bltin-exceptions and includes NameError
, ImportError
, AssertionError
etc.
try
- except
- finally
syntax
try
- except
- finally
is a syntax to handle exceptions in python
, and it helps prevent errors from stopping a program. The syntax is the following:
try:
# Part 1: Normal code goes here
except:
# Part 2: Code for error handling goes here
# This code is not executed unless Part 1
# above generated an error
finally:
# Optional: This clause is executed no matter what,
# and is generally used to release external resources.
Let us consider the following example to understand the syntax better:
try:
print("test_var testing:")
= 4
e print(test_var) # raise an error: the test_var variable is not defined
except NameError:
print("Caught an exception: test_var does not exist")
finally:
print("This code is executed no matter what")
print("The program keep continuing... it does not freeze!")
print(f"Beware! the affectation step: e = {e} was executed.")
test_var testing:
Caught an exception: test_var does not exist
This code is executed no matter what
The program keep continuing... it does not freeze!
Beware! the affectation step: e = 4 was executed.
To obtain some information on the error: it is possible to access the instance of the Exception
class thrown by the program through the following syntax:
try:
print("test")
print(testtt) # Error: the variable testtt is not defined
except Exception as name_exception:
print("Caught an exception:", name_exception)
test
Caught an exception: name 'testtt' is not defined
A common use case is to test if the import of a package was successful or not. For instance, if you try loading a package pooooch
that is not installed on your machine, the following code will raise an error:
import pooooch
--------------------------------------------------------------------------- ModuleNotFoundError Traceback (most recent call last) Cell In[20], line 1 ----> 1 import pooooch ModuleNotFoundError: No module named 'pooooch'
If you would like the program to continue even if the package is not installed, you can use the following syntax:
try:
import pooch
except Exception as e:
print(e)
An exhaustive list of exceptions be found here: https://docs.python.org/3/library/exceptions.html.
The with
statement
You have to run the following lines at a location where a directory called scripts/
containing a function hello-world.py
exists. If you have not cloned the course repository, the file used in the lecture is available here. You can, of course, create your own if you prefer.
= "./scripts/hello-world.py"
fname
with open(fname) as file: # Use file to refer to the file object
= file.read()
data print(data)
# at the end of the code chunk, the file.__exit__() method is called
# (i.e., file.close() is executed automatically)
tatjpjepj.
Now, let us try with a file that does not exist:
= "scripts/hello-world_do_not_exist.py"
fname try:
# 1/0 # Uncomment at some point and run
file = open(fname)
= file.read()
data print(data)
except FileNotFoundError:
print("File not found!")
except (RuntimeError, TypeError, NameError, ZeroDivisionError):
print("Specific Error message 2")
finally:
file.close() # Important line to release access to the file!
File not found!
Scope
The scope of a variable is the part of the program where the variable is accessible. In python
, the scope of a variable is defined by its location in the code (i.e., where you define it).
= 0
e print(e)
for i in range(1):
= 1
e
print(e)
def f():
= 2
e
print(e)
Conclusion: e
is only “visible” inside the function definition. See https://realpython.com/python-scope-legb-rule/ for more information on this topic.
Manipulate file names across platforms
Each OS (Linux, Windows, Mac, etc.) might have a different syntax to describe a file path. The following would avoid naming conflict due to each OS syntax and could be important for your project if you work with colleagues having a different OS from yours.
import os
print(os.path.join('~', 'work', 'src'))
print(os.path.join(os.getcwd(), 'new_directory'))
os.path.expanduser?print(os.path.expanduser(os.path.join('~', 'work', 'src')))
~/work/src
/home/jsalmon/Documents/Mes_cours/Montpellier/HAX712X/Courses/ClassesExceptions/new_directory
/home/jsalmon/work/src
References
- Python official web page and its style and writing recommendation
- Think Python - A free book by Allen Downey.
- Python Essential Reference - a good reference for general Python coding
- Python Data Science Handbook - an excellent book for data science in Python by Jake VanderPlas (associated notebook available online)