![]() ![]() This is exactly what the Data Model (Section 3 of the Python documentation) helps you accomplish. When you do this, the behavior of the function or operator associated with it changes according to that defined in the method. ![]() You must add the corresponding special methods in your class definition to make your object compatible with built-ins and operators. For example, there’s _len_(), corresponding to len(), and _add_(), corresponding to the + operator.īy default, most of the built-ins and operators will not work with objects of your classes. These special methods have a naming convention, where the name starts with two underscores, followed by an identifier and ends with another pair of underscores.Įssentially, each built-in function or operator has a special method corresponding to it. Python does all this using special methods. But you can configure the + operator in such a way that it appends a new item to the cart. Again, someone new to Python would think of implementing a method called append_to_cart() that takes an item and appends it to the cart list. In another case, we might want to append something to the cart. But you can configure the built-in len() in such a way that it returns the length of the cart list when given our object. Someone new to Python might decide to implement a method called get_cart_len() in their class to do this. ![]() In such a case, it is quite natural to want to obtain the length of the cart list. Note: If you need a refresher on OOP in Python, check out this tutorial on Real Python: Object-Oriented Programming (OOP) in Python 3 ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |