![]() ![]() Likewise, you could add new features without fearing that you’ll get tangled up with other pieces of the software. Say you found a bug in one class: you could fix that bug without worrying about the other classes because there is no connection between them. Not only does this keep things neat and tidy it is also a lot easier for maintenance. Thinking in classes not only helps you keep features separate, but also independent of one another. In other words, when you set out writing a program and you’re thinking in terms of classes, you might be building a good architecture because you’re ensuring that each problem has its own place. ![]() It basically means that you split up your program into different sections that deal with different pieces of information.Ĭlasses, by their nature, allow you to keep to that principle. If you’ve attended lectures in computer science, it’s pretty likely that you’ve stumbled across the principle of “separation of concerns”. Separation of concerns: giving every class its own job Photo by Muhannad Ajjan on Unsplash Classes are amazing - in theory Try doing this implementation with standard functions, and you’ll probably have a lot more trouble dealing with it.įrom a theoretical point of view, there are more reasons why Python classes are a beautiful concept in many situations.Ĭlasses are powerful concepts when used right. Deleting an attribute goes like so:Īnd if you want to delete an entire object, you do like so:Īll of this is neat, simple, and expandable. The nicest part of all of this is that you can add and delete as many objects as you like. If you need to add more routines, you can just put them in the class definition. Now, we can add some calls of our methods after the lines where we’ve initialized the instances of the class: We could also add some routines to tell us the price, or to promote an item by reducing the price: We can add a method to set the price directly underneath the _init_ function, within the class definition: This code will run, but it’s not doing very much. We would add these two lines without indent, after the definition of the class. Now, we can define various instances of the class and keep them organized: You could create a class that takes each item of clothing in the shop, and stores key quantities such as the type of clothing, and its color and size. For example, imagine you’re writing a piece of code to organize the inventory of a clothes shop. Python classes: the very basicsĬlasses are objects that allow you to group data structures and procedures in one place. So if you’re in a hurry, you can skip the following two sections and scroll right down to the sections When to use classes and When classes are a bad idea. ![]() This story is a deeper dive into the matter. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |