Code Explanation:
1) Class Definition
class A:
x = 5
Defines a class A.
Inside it, a class attribute x = 5 is declared.
This means x belongs to the class itself, not to instances only.
2) Class Method
@classmethod
def c(cls): return cls.x
@classmethod makes c a method that takes the class itself (cls) as the first argument, instead of an instance.
When A.c() is called:
cls refers to the class A.
It returns cls.x, i.e., A.x = 5.
3) Static Method
@staticmethod
def s(): return 10
@staticmethod makes s a method that does not automatically take self or cls.
It’s just a normal function stored inside the class namespace.
Always returns 10, independent of class or instance.
4) Calling the Class Method
print(A.c())
Calls c as a class method.
cls = A.
Returns A.x = 5.
Output: 5
5) Calling the Static Method
print(A.s())
Calls s as a static method.
No arguments passed, and it doesn’t depend on the class.
Always returns 10.
Output: 10
Final Output
5
10
Download Book - 500 Days Python Coding Challenges with Explanation
.png)

0 Comments:
Post a Comment