# instance methodclass Calculator: def add(self, a, b): return a + bcalc = Calculator()calc.add(5, 3)#ans: 8
# class methodclass Dog: count = 0 def __init__(self): Dog.count += 1 @classmethod def get_count(cls): return cls.countDog().get_count()#ans: 1
# static methodclass MathUtils: @staticmethod def add(a, b): return a + bMathUtils.add(5, 3)#ans: 8 (no instance needed)
# self accesses instanceclass Person: def __init__(self, name): self.name = name def greet(self): return f"Hi, I'm {self.name}"Person("Alice").greet()#ans: "Hi, I'm Alice"
# classmethod vs instance?class MyClass: @classmethod def method(cls): return clsMyClass.method()#ans: <class 'MyClass'>
# staticmethod access?class MyClass: x = 5 @staticmethod def method(): return xMyClass.method()#ans: NameError (no self or cls)
# classmethod receives?class MyClass: @classmethod def method(cls): return type(cls)MyClass.method()#ans: <class 'type'>
# call instance method on class?class MyClass: def method(self): passMyClass.method()#ans: TypeError (missing self)
# staticmethod with self?class MyClass: @staticmethod def method(self): passobj = MyClass()obj.method()#ans: TypeError (no implicit self)
# classmethod inheritance?class Base: @classmethod def who(cls): return cls.__name__class Derived(Base): passDerived.who()#ans: "Derived"
# method chaining?class Builder: def set_x(self, x): self.x = x return self def set_y(self, y): self.y = y return selfBuilder().set_x(1).set_y(2)
# private method?class MyClass: def __private(self): passobj = MyClass()obj.__private()#ans: AttributeError (name mangling)
# method vs function?class MyClass: def method(self): passtype(MyClass.method)#ans: <class 'function'>type(MyClass().method)#ans: <class 'method'>
# alternative constructor?class Point: def __init__(self, x, y): self.x = x self.y = y @classmethod def origin(cls): return cls(0, 0)Point.origin()
Google tag (gtag.js)