How do i use classes in python?
-
The main purpose of python classes is for the reuse of code.
To try and help explain classes, part of object oriented programming, an analogy using cakes, see diagram:
Now the explanation part. All recipes have ingredients, the thing or object you are making is a "cake", using various ingredients, you can make different cakes.
How does this relate to classes in python? Check the diagram below:
- The python class is the recipe.
- The python object is the thing the class is describing.
- The python instances are the various cakes (each can be different, but use the same class)
A very simple code example:
class Cake(object): def __init__(self, type, base): self.type = type self.base = base i1 = Cake('carrot', 'sponge') print(i1.type) print(i1.base) i2 = Cake('fruit', 'sponge') print(i2.type) print(i2.base)
Looking into it a little more the class is made up of methods and variables. Just as a recipe is made up of various types of ingredients. In the code above, there's a method called "init" this is the first code executed when a new instance of the class is created, the init methods; the first parameter is self, but not used when calling the method, As can be seen in the code "i1 = Cake('carrot', 'sponge')".
© Lightnetics 2024