Methods

Instance Methods

  1. # instance method
  2. class Calculator:
  3. def add(self, a, b):
  4. return a + b
  5. calc = Calculator()
  6. calc.add(5, 3)
  7. #ans: 8

Class Methods

  1. # class method
  2. class Dog:
  3. count = 0
  4. def __init__(self):
  5. Dog.count += 1
  6. @classmethod
  7. def get_count(cls):
  8. return cls.count
  9. Dog().get_count()
  10. #ans: 1

Static Methods

  1. # static method
  2. class MathUtils:
  3. @staticmethod
  4. def add(a, b):
  5. return a + b
  6. MathUtils.add(5, 3)
  7. #ans: 8 (no instance needed)

Method with Self

  1. # self accesses instance
  2. class Person:
  3. def __init__(self, name):
  4. self.name = name
  5. def greet(self):
  6. return f"Hi, I'm {self.name}"
  7. Person("Alice").greet()
  8. #ans: "Hi, I'm Alice"

Exercises - Part 1

  1. # classmethod vs instance?
  2. class MyClass:
  3. @classmethod
  4. def method(cls):
  5. return cls
  6. MyClass.method()
  7. #ans: <class 'MyClass'>

Exercises - Part 2

  1. # staticmethod access?
  2. class MyClass:
  3. x = 5
  4. @staticmethod
  5. def method():
  6. return x
  7. MyClass.method()
  8. #ans: NameError (no self or cls)

Exercises - Part 3

  1. # classmethod receives?
  2. class MyClass:
  3. @classmethod
  4. def method(cls):
  5. return type(cls)
  6. MyClass.method()
  7. #ans: <class 'type'>

Exercises - Part 4

  1. # call instance method on class?
  2. class MyClass:
  3. def method(self):
  4. pass
  5. MyClass.method()
  6. #ans: TypeError (missing self)

Exercises - Part 5

  1. # staticmethod with self?
  2. class MyClass:
  3. @staticmethod
  4. def method(self):
  5. pass
  6. obj = MyClass()
  7. obj.method()
  8. #ans: TypeError (no implicit self)

Exercises - Part 6

  1. # classmethod inheritance?
  2. class Base:
  3. @classmethod
  4. def who(cls):
  5. return cls.__name__
  6. class Derived(Base):
  7. pass
  8. Derived.who()
  9. #ans: "Derived"

Exercises - Part 7

  1. # method chaining?
  2. class Builder:
  3. def set_x(self, x):
  4. self.x = x
  5. return self
  6. def set_y(self, y):
  7. self.y = y
  8. return self
  9. Builder().set_x(1).set_y(2)

Exercises - Part 8

  1. # private method?
  2. class MyClass:
  3. def __private(self):
  4. pass
  5. obj = MyClass()
  6. obj.__private()
  7. #ans: AttributeError (name mangling)

Exercises - Part 9

  1. # method vs function?
  2. class MyClass:
  3. def method(self):
  4. pass
  5. type(MyClass.method)
  6. #ans: <class 'function'>
  7. type(MyClass().method)
  8. #ans: <class 'method'>

Exercises - Part 10

  1. # alternative constructor?
  2. class Point:
  3. def __init__(self, x, y):
  4. self.x = x
  5. self.y = y
  6. @classmethod
  7. def origin(cls):
  8. return cls(0, 0)
  9. Point.origin()

Google tag (gtag.js)