Class and Objects
Class and Objects
Since many houses can be made from the same description, we can create
many objects from a class.
class ClassName:
# class definition
class Bike:
name = ""
gear = 0
Here,
objectName = ClassName()
# create class
class Bike:
name = ""
gear = 0
Here, bike1 is the object of the class. Now, we can use this object to access
the class attributes.
Output
In the above example, we have defined the class named Bike with two
attributes: name and gear .
# define a class
class Employee:
# define an attribute
employee_id = 0
Output
Python Methods
We can also define a function inside a Python class. A Python
Function defined inside a class is called a method.
Let's see an example,
# create a class
class Room:
length = 0.0
breadth = 0.0
# method to calculate area
def calculate_area(self):
print("Area of Room =", self.length * self.breadth)
Output
Method: calculate_area()
Here, we have created an object named study_room from the Room class. We
then used the object to assign values to attributes: length and breadth .
Notice that we have also used the object to call the method inside the
class,
study_room.calculate_area()
Here, we have used the . notation to call the method. Finally, the statement
inside the method is executed.
Python Constructors
Earlier we assigned a default value to a class attribute,
class Bike:
name = ""
...
# create object
bike1 = Bike()
However, we can also initialize values using the constructors. For example,
class Bike:
# constructor function
def __init__(self, name = ""):
self.name = name
bike1 = Bike()