Python Classes and Objects - CNDRO.LLC
3160
post-template-default,single,single-post,postid-3160,single-format-standard,wp-custom-logo,theme-bridge,bridge-core-2.9.4,woocommerce-no-js,tribe-no-js,ehf-template-bridge,ehf-stylesheet-bridge-child,qode-page-transition-enabled,ajax_fade,page_not_loaded,,qode-title-hidden,qode_grid_1300,footer_responsive_adv,hide_top_bar_on_mobile_header,columns-4,qode-child-theme-ver-1.0.0,qode-theme-ver-27.8,qode-theme-bridge,qode_header_in_grid,wpb-js-composer js-comp-ver-6.7.0,vc_responsive,elementor-default,elementor-kit-2634

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.
No Comments

Post A Comment