How to Define and Use Class in Python


In this example we will show how to define and use class in Python.

2. Definition of Python Class

#!/usr/bin/python
# -*- coding: UTF-8 -*-

class Stu:

    def __init__(self, name, id):
        self.name = name
        self.id = id

    def displayInfo(self):
        print("Name: ", self.name, ", ID: ", self.id)

Notes:

  • The first method, the init() method, is a special method called a class constructor that is called when an instance of this class is created.
  • self is required as the first argument when defining the methods of the class. This is different from other languages like Java, C++, et al.

3. Use of Python Class

stu = Stu('Christina', 102)
stu.displayInfo()

Output:

Name: Christina, ID:  102
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments