Python Class Properties and Methods

Python tutorial · PySpark.in

What Are Class Properties?

Class properties (also called attributes) are variables that belong either to:

1. Instance Properties (Instance Variables)

2. Class Properties (Class Variables)

Example: Class & Instance Properties

```

class Student:
    # Class property
    school_name = "D.A.V"
    def __init__(self, name, roll):
        # Instance properties
        self.name = name
        self.roll = roll
# Creating objects
s1 = Student("Megha", 101)
s2 = Student("Ravi", 102)
# Accessing instance and class properties
print(s1.name)           
print(s2.roll)             
print(Student.school_name)

```

Explanation

school_name → (Class Property)

name, roll Instance Property

Summary of Property Access

TypeWhat It RepresentsAccess Using
Instance PropertyData unique to each objectobject.property
Class PropertyShared data for all objectsClassName.property

What Are Class Methods?

Methods are functions written inside a class to define behavior.
Python has three types of methods:

Method TypeDescriptionUsesDecorator
Instance MethodWorks with object dataAccess & modify instance variables
Class MethodWorks with class dataModify class variables@classmethod
Static MethodIndependent utility functionHelper logic with no dependency@staticmethod
Example: Instance, Class, and Static Method
PYTHON
1class Student:
2 school_name = "Delhi University" # Class property
3 def __init__(self, name, roll):
4 self.name = name # Instance property
5 self.roll = roll
6 # Instance method
7 def show(self):
8 print(f"Name: {self.name}, Roll: {self.roll}")
9 # Class method
10 @classmethod
11 def change_school(cls, new_name):
12 cls.school_name = new_name
13 # Static method
14 @staticmethod
15 def info():
16 print("This is the Student class for managing student data.")
17# Creating objects
18s1 = Student("Megha", 101)
19s2 = Student("Ravi", 102)
20# Calling instance method
21s1.show()
22# Calling class method
23Student.change_school("D.A.V")
24# Accessing updated class property
25print(Student.school_name)
26# Calling static method
27Student.info()
▶ Output will appear here.

Explanation of Method Types

 Instance Method — show()

Class Method — change_school()

Static Method — info()

More Python tutorials

All tutorials · Try the free PySpark compiler · Practice challenges