Code Explanation:
1️⃣ Defining the Class
class A:
Explanation
A class A is created.
It will contain variables and methods.
2️⃣ Defining Class Variable
x = 10
Explanation
x is a class variable.
It belongs to the class, not individual objects.
3️⃣ Defining @classmethod
@classmethod
def f(cls):
Explanation
f is a class method.
It receives the class itself as cls.
4️⃣ Accessing Class Variable via cls
return cls.x
Explanation
Accesses class variable x using cls.
Works for inheritance too (dynamic reference).
5️⃣ Defining @staticmethod
@staticmethod
def g():
Explanation
g is a static method.
It does NOT receive self or cls.
6️⃣ Accessing Class Variable Directly
return A.x
Explanation
Directly accesses class A.
Not flexible for inheritance (hardcoded).
7️⃣ Calling Methods
print(A.f(), A.g())
Explanation
Calls both methods using class A.
๐ Method Execution
๐น A.f()
cls = A
Returns:
A.x → 10
๐น A.g()
Directly returns:
A.x → 10
๐ค Final Output
10 10

0 Comments:
Post a Comment