Python Object-Oriented Programming Explained in 12 Minutes
By NeuralNine
TechnologyEducationAI
Share:
Object-Oriented Programming in Python: A Quick Tutorial
Key Concepts:
- Class: A blueprint or description of an object.
- Object: An instance of a class.
- Constructor (
__init__): A special method used to initialize objects when they are created. self: A reference to the instance of the class (the object itself).- Dunder Methods (Double Underscore Methods): Special methods in Python that begin and end with double underscores (e.g.,
__init__,__str__,__repr__,__add__). They allow you to overload operators and customize object behavior. - Operator Overloading: Defining how standard operators (e.g., +, -, ==) behave with objects of a class.
- Inheritance: Creating a new class based on an existing class (parent class), inheriting its attributes and methods.
- Super(): Used in a child class to access the methods and properties of the parent class.
- Polymorphism: The ability of different classes to respond to the same method call in their own way.
1. Classes and Objects
- A class is a blueprint for creating objects. It defines the attributes (data) and methods (behavior) that objects of that class will have.
- An object is a specific instance of a class.
- Example:
class Person: Defines the structure of a person (name, age, job).person1 = Person("Mike", 25, "programmer"): Creates an objectperson1based on thePersonclass.
- The
__init__method is the constructor. It's called when an object is created.- It takes
selfas the first argument, which refers to the object being created. - Other arguments can be passed to initialize the object's attributes.
- Example:
class Person: def __init__(self, name, age, job): self.name = name self.age = age self.job = job
- It takes
- Attributes are accessed using dot notation (e.g.,
person1.name).
2. Dunder Methods
- Dunder methods (special methods) allow you to customize how objects behave in various situations.
__str__: Defines how an object is represented as a string when usingprint().__repr__: Defines the "official" string representation of an object, often used in debugging or when the object is displayed in the Python shell.- If
__str__is not defined,__repr__is used whenprint()is called. - If both are defined,
print()calls__str__and simply typing the object's name in the shell calls__repr__.
- If
- Example:
class Person: # ... (init method) ... def __str__(self): return f"Person(name={self.name}, age={self.age}, job={self.job})" def __repr__(self): return f"Person(name={self.name})"
3. Operator Overloading
- Operator overloading allows you to define how standard operators (+, -, ==, etc.) behave with objects of your class.
- This is done by implementing specific dunder methods.
- Example:
Vector3Dclass with overloaded__add__(addition) and__mul__(multiplication) operators. __add__(self, other): Defines the behavior of the+operator.- Checks if
otheris also aVector3Dobject. - If so, adds the corresponding components and returns a new
Vector3Dobject. - Otherwise, raises an error or returns
NotImplemented.
- Checks if
__mul__(self, other): Defines the behavior of the*operator.- Checks if
otheris a scalar (float or integer). - If so, multiplies each component by the scalar and returns a new
Vector3Dobject.
- Checks if
- Other dunder methods for operator overloading:
__sub__(subtraction)__truediv__(true division)__floordiv__(floor division)__eq__(equality)
- Example:
class Vector3D: def __init__(self, x1, x2, x3): self.x1 = x1 self.x2 = x2 self.x3 = x3 def __add__(self, other): if isinstance(other, Vector3D): return Vector3D(self.x1 + other.x1, self.x2 + other.x2, self.x3 + other.x3) else: return NotImplemented def __eq__(self, other): if isinstance(other, Vector3D): return self.x1 == other.x1 and self.x2 == other.x2 and self.x3 == other.x3 else: return False
4. Inheritance
- Inheritance allows you to create a new class (child class) based on an existing class (parent class).
- The child class inherits all the attributes and methods of the parent class.
- You can add new attributes and methods to the child class, or override existing ones.
- Example:
Programmerclass inheriting fromPersonclass. class Programmer(Person): Specifies thatProgrammerinherits fromPerson.super().__init__(name, age, job): Calls the constructor of the parent class (Person) to initialize the inherited attributes.- Example:
class Person: def __init__(self, name, age, job): self.name = name self.age = age self.job = job def print_name(self): print(self.name) class Programmer(Person): def __init__(self, name, age, job, main_language): super().__init__(name, age, job) self.main_language = main_language def __repr__(self): return f"Programmer(name={self.name}, language={self.main_language})" - Multiple Inheritance: A class can inherit from multiple parent classes.
- Example:
FlyingFishinheriting fromFlyerandSwimmer.
- Example:
5. Polymorphism
- Polymorphism means "many forms."
- It allows objects of different classes to respond to the same method call in their own way.
- Example:
Shapeclass witharea()method, andCircle,Square, andTriangleclasses inheriting fromShapeand overriding thearea()method. - Each subclass implements the
area()method differently, according to its specific shape. - Example:
class Shape: def area(self): pass # Abstract method class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return 3.14 * self.radius * self.radius class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side * self.side
Conclusion
This tutorial provides a concise introduction to object-oriented programming (OOP) in Python, covering classes, objects, constructors, dunder methods, operator overloading, inheritance, and polymorphism. It emphasizes practical examples and code snippets to illustrate the core concepts. While not exhaustive, it serves as a solid foundation for further exploration of OOP principles in Python. The video suggests further learning about data classes, encapsulation, name mangling, properties, static methods, and class methods.
Chat with this Video
AI-PoweredHi! I can answer questions about this video "Python Object-Oriented Programming Explained in 12 Minutes". What would you like to know?
Chat is based on the transcript of this video and may not be 100% accurate.