OOP

What is the class?

Class = a program-code-template that allows developers to create an object that has both variables (data) and behaviors (functions or methods).

object = state (attributes) + behavior (methods)

4 basic OOP concepts

EncapsulationAbstractionInheritancePolymorphism

Python class coding tricks

class A:
    class_attr = "a1"

    def __init__(self):
        self.a2 = "a2"

    def check(self):
        return self.class_attr


class B(A):
    class_attr = "b1"

    def __init__(self):
        super().__init__()


b = B()
print(b.check())
# Result: b1
class A:
    def __init__(self):
        self.__a = "Low"
        self.b = "zyx"

    def d(self):
        print(self.__a, self.b)


class AA(A):
    def __init__(self):
        super().__init__()
        self.__a = "Hihg"
        self.b = "ijk"


aaa = AA()
aaa.d() 

# Q: What will be printed in screen?
# Low adf
class A:
    x = 2


class B(A): ...


class C(A): ...


def print_x():
    print(A.x, B.x, C.x)


print_x()  

B.x = 4
print_x()  

A.x = 5
print_x()  

# Q: What will be printed in screen?
# 2 2 2
# 2 4 2
# 5 4 5
image

Best practices

  1. Set attributes in the constructor.
  2. Distinguish class-level and instance-level data and methods.
  3. Determine what is equal.
  4. Provide string representations.
  5. Know what is static.
  6. Decide what is internal and private.
  7. Set access to attributes.
  8. Use docstrings.

Resources

SuperMade with Super