Code Explanation:
๐น 1. Class Definition
class Test:
✅ Explanation:
A class named Test is created.
It will contain a variable and two methods.
๐น 2. Class Variable
x = 10
✅ Explanation:
x is a class variable.
Shared across all instances of the class.
Accessible via:
Test.x
cls.x (inside class methods)
๐น 3. Class Method (@classmethod)
@classmethod
def show(cls):
return cls.x
✅ Explanation:
@classmethod decorator defines a method that works with the class, not instance.
cls refers to the class (Test).
๐ What happens:
cls.x → accesses class variable x
Returns:
10
๐น 4. Static Method (@staticmethod)
@staticmethod
def display():
return Test.x
✅ Explanation:
@staticmethod creates a method that:
Does NOT take self or cls
Works like a normal function inside the class
๐ What happens:
Directly accesses:
Test.x
Returns:
10
๐น 5. Calling Methods
print(Test.show(), Test.display())
✅ Step-by-step:
➤ Test.show()
Calls class method
cls = Test
Returns:
10
➤ Test.display()
Calls static method
Returns:
10
๐ฏ Final Output
10 10

0 Comments:
Post a Comment