How to create classes and objects in python ?
Today we will look how to create classes and object of these classes in python.
To understand how to define classes and create its objects, lets have a look at an example.
Defining classses and creating its objects
$ cat classes.py #!/usr/bin/python ### creating class named student. ### 2 variables "name" and "student are defined" ### One function called "attitude" is also defined. class student: name = "" percentage = 0 def attitude(self): att = "%s is a good person with overall percentage %.2f" % (self.name, self.percentage) return att ### Creating two objects of student class student1=student() student2=student() ### Changing default values of these two objects. student1.name="Mohit" student2.name="Rohit" student1.percentage=70 student1.percentage=80.23 ### Printing the function call, not values print(student1.attitude) print(student2.attitude) ### Getting the return values in two variables. a=student1.attitude() b=student2.attitude() ### printing return values print a print b $
Output
$ ./classes.py < bound method student.attitude of < __main__.student instance at 0x108167c20 >> < bound method student.attitude of < __main__.student instance at 0x108167c68 >> Mohit is a good person with overall percentage 80.23 Rohit is a good person with overall percentage 0.00 $