Classes In Python
Class
is a very powerful feature of object-oriented programming. In Python, we first write a class
to mimic any real word scenario and then create object
based on this class
. In this way, when we create individual object
from the class
, each object
is automatically equipped with the general behavior of a class
; however, we can give each object
whatever unique features we desire.
Making an
object
from aclass
is called instantiation, and we work with instances of a class.
1. CREATING AND USING A CLASS
Letβs write our first class, Restaurant
with two parameters ( restaurant_name
and cuisine_type
) and three methods ( __init__()
, describe_restaurant
and open_restaurant
)
Using this class
, we can write any instance
with the access to these methods:
1.1. Creating a Class
Method: a
function
that is part of aclass
is called methodSpecial Method:
__init__()
is a special method and it is required. Python runs this automatically whenever we create a newobject
based on theclass
.Parameters of Special Method: the
__init__()
method have three parameters:self
,restaurant_name
andcuisine_type
. Theself
parameter is required in the method definition, and it must come first, before the other parametersAttributes: any variable prefixed with self is called an attribute. Attributes are available to every method in the
class
, and we can also access these variables(attributes) through anyinstance
created from theclass
.Other Defined Methods: the
Restaurant
class has two other methods:describe_restaurant
andopen_restaurant
Because these methods donβt need additional information (parameters), we just define them to have one parameter,self
.
1.2. Making instances of Class
a. Making instance
this line tells Python to create an instance(object),
restaurant
whoserestaurant_name
value isarabian nights
andcuisine_type
ismiddle eastern
. When Python reads this line, it calls the__init__()
method inRestaurant
class with the argumentsarabian nights
andmiddle eastern
the
__init__()
method creates aninstance
representing this particular restaurant and sets therestaurant_name
andcuisine_type
using the values providedyou can create as many instances from a class as you need.
b. Accessing Attributes
To access these attributes value directly we use dot notation β restaurant.restaurant_name
and restaurant.cuisine_type
The syntax is essentially instance_name.parameter_name
c. Calling Methods
We can also use dot notation to call any method defined in Restaurant
β restaurant.describe_restaurant()
and restaurant.open_restaurant()
d. Output
2. WORKING WITH CLASSES AND INSTANCES
In this section, we will learn how to set a default value for attributes and, three ways to modify attributes value. We will use the previous example of class Restaurant
in this section.
2.1. Setting a Default Value for an Attribute
Every
attribute
in aclass
needs an initial value, even if that value is 0 or an empty string. We can specify this initial value in the body of the__init__()
method; *if we do set a default value for an attribute, we donβt have to include a parameter for that attribute in method definition *
Letβs add an attribute called numbers_served
and set its default value to 0
As we have specified the default value of self.numbers_served
, we donβt need to mention the parameter numbers_served
in the __init__()
We are going to create an instance and print the (default) attribute value for numbers_served
2.2. Modifying Attribute Values
We will use three methods to modify an attribute value:
a. Modifying an Attribute Value Directly
The simplest way to modify the value of an attribute is to declare the new value in the instance of the class. Here, we will modify the default value of attribute numbers_served
to 100
b. Modifying an attributeβs Value through a Method
Instead of modifying the attribute value directly, we can pass the new value to a method (set_numbers_served
) that handles the updating internally.
Note: In the following example, we could set the new value without using if
statement, but that will make the code open to errors where new value can be lower than the old value of numbers_served
Then we call this new method:
c. Incrementing an attributeβs Value through a Method
Sometimes we want to increment an attributeβs value by a certain amount rather than set an entirely new value. Hereβs a method that allows us to pass this incremental amount and add that value to the existing value of numbers_served
Letβs make an instance and call this new method:
3. INHERITANCE
In this section we will study the parent-child class structure. If the class we are writing (child) is a specialized version of another class (parent) that we wrote before, we can use inheritance structure
The original class is called the parent class (superclass), and the new class is the child class (subclass)
The child class automatically inherits all attributes and methods from its parent class but at the same time, can define new attributes and methods of its own
Rule 1: When we create a child class, the parent class must be part of the current file
Rule 2: When we create a child class, the parent class must appear before the child class in the file
Rule 3: The name of the parent class must be included in parentheses
()
in the definition of the child class
3.1. Creating Child Class from Parent Class
Letβs create a child class, IceCreamStand
from parent class, Restaurant
a. Creating Child Class
we created the child class,
IceCreamStand
by providing the name of parent class,Restaurant
within its parenthesis βIceCreamStand(Restaurant):
The
__init__()
method takes in the required parameters from the parent class,Restaurant
The
super().__init__
function is a special function that helps Python make connections between the parent and child class. This line tells Python to call the__init__()
method in parent class, which gives child class all the attributes of its parent classthen, we defined the attribute
self.flavors
specific to child class. This supposed to belist
, so we gave it an empty list default value[]
then, we defined a method,
display_flavors(self)
that is specific to child class. This method used theself.flavors
attribute and print the value of each item in the list
b. Creating Instance of Child Class
we created an instance of child class (
IceCreamStand
),icecreamstand_1
Arguments provided aredairy queen
, andice cream
then we call a method, which is defined in the parent class to demonstrate how the inheritance works
then we provided the attribute (
icecreamstand_1.flavors
) that is specific to child class (IceCreamStand
) and call the method (icecreamstand_1.display_flavors()
)that is also specific to child class
3.2. Overwriting Methods from the Parent Class
We can overwrite any method from the parent class when creating a child class. To do this, we define a method in the child class with the same name as the method we want to overwrite from the parent class. Python intelligently uses the method that we defined in the child class.
3.3. Instances as Attributes
When our program start becoming lengthier and messier, we can break it down into various classes, where an instance of class can become an attribute of another class. The example below will help understand this concept:
we first defined the class (
Privileges
) that will be used as an attribute in other class (User
)Privileges
class has only one method,show_priviledges
then while defining the
User
class, we give it an attribute ofprivileges
that takes its value from instance ofPrivileges
class
then we created an instance of
User
, namedadmin_user
and provided the arguments
finally we call the
show_privileges
method ofPrivilege
class, as an attribute ofUser
class
4. IMPORTING CLASSES
The method to import class(es) from modules is similar to what we have covered in the Part 7: Functions in Python
4.1. Importing a Single Class
In theory, we can store as many classes as we need in a single module, but it is good is each class in a module are related
a. Syntax to import
The import statement tells Python to open the module and import the class, class_name
.
b. Syntax to create instance
The syntax to create instance
is same as if the class
is defined in the same file
4.2. Importing Multiple Classes from a Module
a. Syntax to import
You import
multiple classes from a module by separating each class
with a comma
b. Syntax to create instance
The syntax to create instance
is same as if the class
is defined in the same file
4.3. Importing an Entire Module
We can also import an entire module and then access the classes
you need using dot notation. Therefore, we need to use the module name whenever creating the instance
a. Syntax to import
b. Syntax to create instance
4.4. Importing All Classes from a Module
We can import all classes using the syntax defined in section 4.3. Then why do we need to import
all classes
from module using this method? Because this way, we donβt need to use the dot notation.
a. Syntax to import
b. Syntax to create instance
ALERT: This method to import classes is not recommended
4.5. Importing a Module into a Module
One module maybe dependent on other modules, therefore, at the start of file, we can import other modules and required classes, using syntax
The syntax to create instance is same as if the class is defined in the same file
Last updated
Was this helpful?