26 Apr Python Classes and Objects
A class is a user-defined blueprint for creating Objects. When we create a new class, we also create a new object. We can also call class an object constructor for creating objects.
An object can be defined as an instance of a class for which class acts as a blueprint for an object.
For instance, we have species of birds that have certain attributes and we want to name 20 of them. Instead of creating a class for each bird, we just need to instantiate the multiple objects of that particular class.
Like function begins with the def keyword when defining it, class definitions also begin with a class keyword.
Create a Class
A simple class Definition
1class MyStudents:
2 '''This is a simple class definition'''
3 pass
Create an Object
Creating an object of a class
1 Object_name= MyStudents()
Class and Object Example
Let’s check out this first example using a Bird specie as our class whereby we create an object of the Birds class as AsianGoose .We will use the object to call the function available in the class.
1class Birds: 2 "This is a person class" 3 feathers="yes" 4 5 def Fly(self): 6 print('Flying') 7 8 9# create a new object of Birds class 10AsianGoose = Birds() 11 12# Output: <function Birds.Fly> 13print(Birds.Fly) 14 15# Calling object's Fly() method 16# Output: Flying 17print(AsianGoose.Fly())
The __init__() Method of Class
Any double underscore before and after the variable and method are referred to as special variable and method in Python. e.g., So __name__ is a special variable, whereby __age__() is a special method.
Whenever we use the __init__() method, it acts like constructor whereby on creating an object of the class, it automatically calls this method once.
An example is implemented below on the init method of a class. In this example, we created a Class of MyStudent and define our constructor and as well use the self as the instance of the objects. We have access to the displayStudent function whenever we define the object of the class Mystudent, which allows us to have access to the name, and age parameter we defined.
1class MyStudent: 2 allStudent = 0 3 4 def __init__(self, name, age): 5 self.name = name 6 self.age = age 7 MyStudent.allStudent += 1 8 9 def displayStudent(self): 10 print("Name:", self.name, end="") 11 print("\tage:", self.age) 12 13 14student1 = MyStudent("Grace Jackson", 15) 15student2 = STUDENT("Sharon. Tyler", 12) 16student3 = STUDENT("Benson Kemony", 16) 17 18student1.displayStudent() 19student2.displayStudent() 20student3.displayStudent()
Hope you found this post helpful. Follow for more posts. Thanks for reading.
No Comments