
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Creating Classes in Python
The class statement creates a new class definition. The name of the class immediately follows the keyword class followed by a colon as follows −
class ClassName: 'Optional class documentation string' class_suite
- The class has a documentation string, which can be accessed via ClassName.__doc__.
- The class_suite consists of all the component statements defining class members, data attributes and functions.
Example
Following is the example of a simple Python class −
class Employee: 'Common base class for all employees' empCount = 0 def __init__(self, name, salary): self.name = name self.salary = salary Employee.empCount += 1 def displayCount(self): print "Total Employee %d" % Employee.empCount def displayEmployee(self): print "Name : ", self.name, ", Salary: ", self.salary
- The variable empCount is a class variable whose value is shared among all instances of a this class. This can be accessed as Employee.empCount from inside the class or outside the class.
- The first method __init__ is a special method, which is called class constructor or initialization method that Python calls when you create a new instance of this class.
- You declare other class methods like normal functions with the exception that the first argument to each method is self. Python adds the self argument to the list for you; you do not need to include it when you call the methods.
- Related Articles
- Data Classes in Python (dataclasses)
- Interpreter base classes in Python
- Creating Instance Objects in Python
- Creating Database Table in Python
- How to define classes in Python?
- Abstract Base Classes in Python (abc)
- Python Exception Base Classes
- Creating a Proxy Webserver in Python
- Introduction to Classes and Inheritance in Python
- How data hiding works in Python Classes?
- How to use enums in Python classes?
- Does Python have “private” variables in classes?
- Creating a button in tkinter in Python
- Creating child process using fork() in Python
- Creating a Frameless window in Python Tkinter

Advertisements