Python OOP
Python OOP
3
Abstraction
Polymorphism
class Person: # Class definition
def __init__(self, name, age): # Constructor method with 2 params
self.name = name # Attribute name
self.age = age # attribute age
# Example usage
if __name__ == "__main__":
person1 = Person("Alice", 30) # Create an instance of Person
person2 = Person("Bob", 25) # Create another instance of Person
• Class: A template of a concept with its properties (attributes) and behaviour (methods).
• Object: An instance of a class. Concrete entity created from the class.
• Encapsulation: Bundling data and methods (code) within a single entity (class).
• Abstraction: Hide details and show only essential information.
• Inheritance: A class can inherit attributes and methods from another class.
• Polymorphism: The ability to use the same method name with different behavior.
• Composition: An attribute can be an object of another class
Constructor : __init__
def increment(self):
self.count += 1
Class methods have only one specific
difference from ordinary functions def decrement(self):
• they have an extra variable that has to be self.count -= 1
added to the beginning of the parameter list def reset(self):
• but we do not give a value for this self.count = 0
parameter when we call the method.
def get_count(self):
• this particular variable refers to the object return self.count
itself,
• and by convention, it is given the name self. def set_count(self, count):
self.count = count
Access Modifiers : Public, private and protected
• All member variables and methods are
class Test:
public by default in Python varPublic = 10
• Protected : By prefixing the name of _varProtected = 20
__varPrivate = 30
your member with a single underscore
def publicMethod(self):
• Private : prefixed with at least print("Public Method")
two underscores
def _protectedMethod(self):
print("Protected Method")
def __privateMethod(self):
print("Private Method")
class Animal:
def speak(self):
• Inheritance mechanism allows you to pass
bird = Bird("Tweety")
print(bird.speak(3))
Polymorphism class Animal:
def __init__(self, name):
self.name = name
# Example usage:
v1 = Vector(1, 2, 3)
v2 = Vector(4, 5, 6)
# Example usage:
# frac1 = Fractional(1, 2)
# frac2 = Fractional(3, 4)
# print(frac1 + frac2) # Output: 5/4
# print(frac1 > frac2) # Output: False
# fract3 = Fractional(42, 0) ???
Now, you can reactivate Copilot!