"The great benefit of classes is that they keep data and functions organized togther. The functions within a class are called \"methods\" and always take the first parameter, \"self\".\n",
"\n",
"With small pieces of code, this is not so important, but as the size of software grows larger, this is handy for keeping things organized. Most Python libraries make extensive use of classes.\n",
"\n",
"A class is like a template and multiple instances of this template can be created.\n",
"\n",
"## Creating an instance of a class\n",
"\n",
"Class definitions can have a special method caled `__init__()`. This initialization method, also called constructor, is called when an instance of a class is created. It is used to store variables and perform other setup."
" # (This could alternatively be done with `self.mass += amount`.)\n",
" self.mass = self.mass + amount\n",
" def exercise(self,amount):\n",
" self.mass = self.mass - amount\n",
" \n",
"x = Insect(\"Bombus terrestris\", 200)\n",
"x.print_description()\n",
"x.eat(10)\n",
"x.exercise(5)\n",
"x.print_description()\n",
"\n",
"y = Insect(\"Apis mellifera\", 100)\n",
"y.print_description()\n",
"# y.eat(10)\n",
"# y.print_description()\n",
"\n",
"z = Insect(\"Tarantula gigantus\", 10, mass_units=\"grams\") # yes, it's not really an insect...\n",
"z.print_description()\n",
"\n",
"# print(x.species_name,x.mass)\n",
"# print(y.species_name,y.mass)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can see we access the value of a variable within a method using `self.variable_name`. Outside the function, we can also access the \"instance variables\" but we need to use the instance name and a dot:"
"As mentioned, most Python libraries make use of classes to organize their code. All objects in Python act a lot like instances of classes. For example, the string methods `.strip()` and `.format()` could be defined on a hypothetical `String` class exactly like the methods above. (In reality, they are likely implemented differently for performance reasons.)"