Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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_suiteconsists of all the component statements defining class members, data attributes and functions.
Basic Class Structure
A Python class contains attributes (data) and methods (functions). Here's the basic syntax ?
class Employee:
'Common base class for all employees'
empCount = 0 # Class variable
def __init__(self, name, salary):
self.name = name # Instance variable
self.salary = salary # Instance variable
Employee.empCount += 1
def displayCount(self):
print("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
print("Name:", self.name, ", Salary:", self.salary)
# Creating instances
emp1 = Employee("John", 50000)
emp2 = Employee("Alice", 60000)
emp1.displayEmployee()
emp2.displayEmployee()
emp1.displayCount()
Name: John , Salary: 50000 Name: Alice , Salary: 60000 Total Employee 2
Key Components
Class Variables vs Instance Variables
class Student:
school = "ABC School" # Class variable (shared by all instances)
def __init__(self, name, grade):
self.name = name # Instance variable (unique to each instance)
self.grade = grade # Instance variable
# Creating instances
student1 = Student("Bob", "A")
student2 = Student("Carol", "B")
print("School:", Student.school) # Access class variable
print("Student 1:", student1.name, student1.grade)
print("Student 2:", student2.name, student2.grade)
School: ABC School Student 1: Bob A Student 2: Carol B
The __init__ Method
The __init__ method is a special method called the constructor. It initializes new instances of the class ?
class Car:
def __init__(self, brand, model, year):
self.brand = brand
self.model = model
self.year = year
def display_info(self):
return f"{self.year} {self.brand} {self.model}"
my_car = Car("Toyota", "Camry", 2023)
print(my_car.display_info())
2023 Toyota Camry
Class Methods and Self Parameter
| Component | Description | Example |
|---|---|---|
| Class Variable | Shared by all instances | empCount = 0 |
| Instance Variable | Unique to each instance | self.name = name |
| Constructor | Initializes new instances | __init__(self, ...) |
| Instance Method | Functions that operate on instances | def method(self): |
Conclusion
Python classes use the class keyword to define blueprints for objects. The __init__ method initializes instances, while self refers to the current instance. Class variables are shared among all instances, while instance variables are unique to each object.
Advertisements
