Tag: object-oriented programming
Technology always evolves. What are classes and where do they come from?
In the very early days of computing, programmers wrote only commands.
Reusable group of statements, helped to structure that code and it improved readability.
Classes are used to create objects which have functions and variables. Strings are examples of objects: A string book has the functions book.replace() and book.lowercase(). This style is often called object oriented programming.
Lets take a dive!
Python Programming Bootcamp: Go from zero to hero
We can create virtual objects in Python. A virtual object can contain variables and methods. A program may have many different types and are created from a class. Example:
Run this program. In this code we have 3 virtual objects: james, david and eric. Each object is instance of the User class.
In this class we defined the sayHello() method, which is why we can call it for each of the objects. The init() method is called the constructor and is always called when creating an object. The variables owned by the class is in this case “name”. These variables are sometimes called class attributes.
We can create methods in classes which update the internal variables of the object. This may sound vague but I will demonstrate with an example.
We define a class CoffeeMachine of which the virtual objects hold the amount of beans and amount of water. Both are defined as a number (integer). We may then define methods that add or remove beans.
We do the same for the variable water. As shown below:
Run this program. The top of the code defines the class as we described. The code below is where we create virtual objects. In this example we have exactly one object called “pythonBean”. We then call methods which change the internal variables, this is possible because we defined those methods inside the class. Output:
If you are new to Python programming, I highly recommend this book.