Skip to content

Instantly share code, notes, and snippets.

@matthewfeickert
Last active May 17, 2020 05:45
Show Gist options
  • Save matthewfeickert/e18057036b7137c5110c418d9bc6bd36 to your computer and use it in GitHub Desktop.
Save matthewfeickert/e18057036b7137c5110c418d9bc6bd36 to your computer and use it in GitHub Desktop.
Example for Anna

Example of Python classes and the use of self

Click this button to run an example in Binder:

Binder

As you can see from requirements.txt I've added some fun Python libraries, that are available in the Binder instance so you can use them in this sandbox environment.

Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Worthwhile reading:\n",
"- [Python language documentation on Classes](https://docs.python.org/3/tutorial/classes.html)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"> Warning: I'm using [Python 3 \"f-strings\"](https://realpython.com/python-f-strings/). These don't exist in Python 2."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"class Example:\n",
" # This is how we define an initialization of all instances of the class\n",
" def __init__(self, data):\n",
" # Assign the user arguments to the class 'data' member\n",
" self.data = data\n",
" \n",
" def info(self):\n",
" print(f\"The data held in this class is {self.data} of type {type(self.data)}\")"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"specific_example = Example([1,2,3,4,5])"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[1, 2, 3, 4, 5]"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"specific_example.data"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The data held in this class is [1, 2, 3, 4, 5] of type <class 'list'>\n"
]
}
],
"source": [
"specific_example.info()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A typical example that you'll see a lot in tutorials is a `Point` class"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"import math # This would normally be done at the top of a file\n",
"\n",
"class Point:\n",
" def __init__(self, x, y, name=None):\n",
" self.x = x\n",
" self.y = y\n",
" if name is None:\n",
" name=\"point\"\n",
" self.name = name\n",
" \n",
" def info(self):\n",
" print(f\"{self.name} {self.x, self.y}:\\n\")\n",
" print(f\"\\t* Cartesian distance from origin: {self.distance():0.3f}\\n\")\n",
" print(f\"\\t* Angle from origin in radians: {self.angle():0.3f}\\n\")\n",
" print(f\"\\t* Angle from origin in degrees: {self.angle()*180./math.pi:0.3f}\")\n",
" \n",
" def distance(self):\n",
" return math.sqrt(self.x**2 + self.y**2)\n",
" \n",
" def angle(self):\n",
" try:\n",
" return math.acos(self.x/self.distance())\n",
" except ZeroDivisionError:\n",
" return 0"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"point (1, 1):\n",
"\n",
"\t* Cartesian distance from origin: 1.414\n",
"\n",
"\t* Angle from origin in radians: 0.785\n",
"\n",
"\t* Angle from origin in degrees: 45.000\n"
]
}
],
"source": [
"positive_quadrant = Point(1,1)\n",
"positive_quadrant.info()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"`self` is an conventional name used to refer to an instance of the class. It is used to draw a distinction between the class itself (a description) and an object that is an instance of the class. In the below we can get the same result by creating an instance of the `Point` class, and then accessing its `distance` method which implicitly uses the instance of the class as `self`, as when we explicitly pass the instance of the class into class definiton. In essence, `self` allows us some \"syntactic sugar\" of being able to just call the class methods from the object."
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"origin = Point(0,0)\n",
"origin.distance() == Point.distance(origin)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.5"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
numpy
scipy
matplotlib
jupyter
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment