Something about parameter binding
Function is stored as the attribute of class, as you can see in the code followed.
class Pizza(object): |
You can find the result like this, <unbound method Pizza.get_size>. It shows the attribute of the function get_size is not bound to any class. And if we try to make this fuction work like this.
Pizza.get_size() |
Will traceback unbound method get_size() must be called with Pizza instance as first argument. And it is clear that, if we can’t call this function because it’s not bound to any instance of Pizza. And we need to make it like this.
Pizza.get_size(Pizza(42)) |
If you want to see where the bound function binds to, try this.
m = Pizza(42).get_size |
I will give some codes about staticmethod of Python
Some codes to learn Staticmethod of Python
class Pizza: |
Here @staticmethod is a marker to begin the staticmethod which lead the defination of mix_ingredients a static fuction. When we make it a staticmethod, we can make the instance x, y not self. In this way, when we have the function, we don’t need to input Pizza().mix_ingredients(1, 2) again, input Pizza.mix_ingredients(1, 2)is OK. To make a comparation, we give another function, cook, which is not a statcimethod, and in this situation, we must define a instance to Pizza(), and only in this way, the function of self will pass to Pizza().
The class method
See this code.
import math |
What is a class method, it’s a function bound to class not instance. And the first parameter must be the cls class itself. And when the function is bound to cls, if we delelte the base_class, the classmethod will still work well. The other side, the staticmethod will not be that lucky, it will call a error as seen followed:
# Using the staticmethod |
The abstract method
The abstract method is defined in a base_class, but will not get any achievement until this function is inherited to the subclass.
import abc |
Ok let’s make an exercise mixed with all of the methods:
import abc |