Skip to content
Object-Oriented Programming in Python
Object-Oriented Programming in Python
Take Notes
Add notes about the concepts you've learned and code cells with code you want to keep.
Add your notes here
# Add your code snippets hereObject
- = state + bahaviour
- treat class as blue print, outlining states and bahaviours
- state <-> attributes
- behaviour <-> methods
list all attrs and methods
dir(object)
def __init__(self, attr1, attr2):
# is a constructor that is called every time an instance of a class is created
    self.attr1 = value
    self.attr2 = valueBest practice
- CamelCase for class name and lower_snake_case for methods and attributes.
- use docstring
Core Principles of OOP
Instance Level Data
- instance attrs created when initializing an instance of a class.
- self binds to an instance
Class Level Data
- Data shared between all instance of a class
- Define the class attr in the body of a class
- Not using self but class name when refering to it
class X:
    MIN_VALUE = value
    def __init__(self, attr):
        ...
        X.MIN_VALUEClass methods
- Methods are already shared: same code for every instance
- Class methods can't use instance-level data
But why a class method?
- Alternative way to a constructor (init())
Use class method to create an object
return cls()will call__init__
def X:
    @classmethod
    def this_method(cls, args...):
        name = value
        return cls(name)
        
X.this_method(args)Class Inheritance
class Child(Parent):
    # Both Child and Parent are defined classes
    def __init__(self, attr1, attr2)
        Parent.__init__(self, attr1)
        self.attr2 = valueOperator Overloading: Comparison
Overloading eq()
def __eq__(self, other):
is called when 2 objects of a class are compared using ==
return (self.id == other.id) and (self.attr1 == other.attr1)
Operator Overloading: String Representation
return the printable presentation of an object but not pointer.
- 
__str__()- print(obj), str(obj)
- informal, for end user
- _str_ing representation
 
- 
__repr__()- printing in console without calling print explicitly
- formal, for developer
- _repr_oducible _repr_esentation
- fall back for print