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.

Create a Class

1class MyStudents: 
2    '''This is a simple class definition''' 
3    pass

Create an Object

1 Object_name= MyStudents()

Class and Object Example

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

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.