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)
-
Unique for each object
-
Stored inside the object
Accessed using
self
2. Class Properties (Class Variables)
-
Shared by all objects of the class
-
Stored inside the class
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)
-
Shared by all students
-
Access using:
-
Student.school_name(recommended) -
s1.school_name(works, but not preferred)
-
name, roll → Instance Property
-
Different for every student
-
Access using:
-
object.property
-
Summary of Property Access
| Type | What It Represents | Access Using |
|---|---|---|
| Instance Property | Data unique to each object | object.property |
| Class Property | Shared data for all objects | ClassName.property |
What Are Class Methods?
Methods are functions written inside a class to define behavior.
Python has three types of methods:
| Method Type | Description | Uses | Decorator |
|---|---|---|---|
| Instance Method | Works with object data | Access & modify instance variables | — |
| Class Method | Works with class data | Modify class variables | @classmethod |
| Static Method | Independent utility function | Helper logic with no dependency | @staticmethod |
Explanation of Method Types
Instance Method — show()
-
Works with object data
First parameter →
selfCalled using:
object.method()
Class Method — change_school()
-
Works with the class, not the object
-
First parameter →
cls -
Can modify class variables
-
Called using:
ClassName.method()
Static Method — info()
-
Does NOT use
selforcls -
Helper/utility function inside the class
-
Called using:
ClassName.method()
More Python tutorials
- What is Python and Why is it used for Data Science and Data Engineering?
- How Does Python Work in the Backend? Internal Working of Python
- Top 30 Python Interview Questions for Data Science
- 3-Month Python Roadmap to Excel in Data Science and Machine Learning
- Python Data Types Explained – A Beginner’s Guide
- test
All tutorials · Try the free PySpark compiler · Practice challenges