I am used to statistical programming and use self-defined functions a
lot in R. In my research work, a self-defined function works well in
most cases since the scalability and flexibility of codes are less of
concern. However, as using more Python and reading more source codes of
Python packages, I find class is an important object and
deserves a brief study on it.
A class is a prototype for an object, from which new instances can be created. An instance is a copy of the class with actual values.
Class Object
A given class object consists of two components:
- State: Attributes/properties of an object
- Behavior: Methods of an object
All the instances share the attributes and the methods of the class. But the values of attributes are unique for each instance. Let's see an example as follows.
1 | # Define a python class named 'makecake' |
makecakeis the class name.
cookandprice_lbare the class attributes, representing the cook and the unit price of a cake.
price()is the class method used to calculate the cake price.
__init__method is a preserved method for a class object, used to initializing its state. The__init__method is executed at the time the class is instantiated (i.e., the creation of an instance).
selfis a must-have parameter in each class method, though it might take no arguments. When we call a method of an object asmyobject.method(arg1, arg2), it is equivalent to the command thatMyClass.method(myobject, arg1, arg2).
Also, note that weight is a variable unique to each
instance, while cook, price_lb,
price() are class variables shared by all
instances of the class.
1 | cake = makecake(weight=2) |
1 | Sharon |
Inheritance
Inheritance allows us to define a class that inherits all the methods
and properties from another class. For example, inherited from
makecake, I declare a new class ordercake as
follows.
1 | # Define a python class based on 'makecake' |
1 | myorder0 = ordercake(weight=2) |
1 | Receipt |
In addtion to the inherited attributes, I add another attribute
tax_rate in the ordercake class to calculate
the cake price after tax such that
1 | myorder1 = ordercake(weight=2, tax_rate = 0.08) |
1 | Receipt |
1 | myorder1.checkout(tip=2) |
1 | Receipt |
Use Self-defined Function in Class
To enhance the ordercake class, I add an additional
function to determine the delivery fee as follows.
1 | # Define a free-delivery function |
A delivery fee of 5 dollars is added to the receipt if the cake price is less than 15 dollars.
1 | myorder2 = ordercake_delivery(weight=2, delivery=free_delivery) |
1 | Receipt |
In contrast, the delivery fee is waived if the cake price is 15 dollars or above.
1 | myorder3 = ordercake_delivery(weight=3, delivery=free_delivery) |
1 | Receipt |
Reference
Python Classes and Objects at GeeksforGeeks: https://www.geeksforgeeks.org/python-classes-and-objects/
View / Make Comments