11.1 Object-oriented programming basics

3 min readjune 24, 2024

Object-oriented_programming_0### (OOP) is a programming paradigm that organizes code into objects, combining data and behavior. It's built on four core principles: encapsulation, abstraction, inheritance, and polymorphism. These concepts mirror real-world relationships and interactions, making code more intuitive and reusable.

In Python, OOP is implemented through classes and objects. Classes serve as blueprints, defining attributes and methods, while objects are instances of these classes. Encapsulation protects data, abstraction simplifies complex systems, inheritance promotes code reuse, and polymorphism enables flexibility in object interactions.

Object-Oriented Programming (OOP) Fundamentals

Core principles of object-oriented programming

Top images from around the web for Core principles of object-oriented programming
Top images from around the web for Core principles of object-oriented programming
  • Encapsulation bundles data and methods into a single unit () relates to real-world entities having properties and behaviors (car encapsulating attributes like color, model, and methods like start(), stop())
  • Abstraction simplifies complex systems by hiding unnecessary details focuses on essential features and behaviors relates to how we interact with real-world objects without knowing their internal workings (driving a car without understanding the engine's intricacies)
  • Inheritance creates new classes based on existing classes inherits attributes and methods from the parent class relates to real-world hierarchical relationships and shared characteristics (sedan class inheriting from a car class, sharing common properties like wheels and doors)
  • Polymorphism allows objects of different classes to be treated as objects of a common parent class enables code reusability and flexibility relates to how different real-world entities can share common behaviors (different vehicle classes like car, truck, motorcycle sharing a common like start())

Encapsulation for data protection

  • Encapsulation in Python achieved using access modifiers (public, protected, private)
    • Public members accessible from anywhere, denoted by no underscore prefix
    • Protected members accessible within the class and its subclasses, denoted by a single underscore prefix (
      _
      )
    • Private members accessible only within the class, denoted by a double underscore prefix (
      __
      )
  • Getter and setter methods used to access and modify private attributes
    • Getter methods retrieve the value of a private
    • Setter methods modify the value of a private attribute
    • Provide controlled access to private attributes (get_name(), set_age())
  • Property decorators provide a Pythonic way to define getter, setter, and deleter methods
    • Use the
      [@property](https://www.fiveableKeyTerm:@property)
      decorator for getter methods
    • Use the
      @<attribute_name>.setter
      decorator for setter methods
    • Simplify the usage of getter and setter methods (employee.name instead of employee.get_name())

Abstraction in Python classes

  • Abstract classes cannot be instantiated directly serve as a blueprint for other classes contain one or more abstract methods (declared but not implemented) defined using the (Abstract Base Class) module in Python
  • Abstract methods declared in an abstract class but not implemented must be implemented by concrete subclasses defined using the
    [@abstractmethod](https://www.fiveableKeyTerm:@abstractmethod)
    decorator
  • Concrete classes are subclasses of abstract classes provide implementations for all abstract methods defined in the abstract class can be instantiated directly
  • Abstraction example:
    1. Abstract class: Shape (with abstract methods like area(), perimeter())
    2. Concrete classes: Circle, Rectangle (implementing the abstract methods)
    3. Users interact with the concrete classes, hiding the complexity of the shape hierarchy

Class and Object Fundamentals

  • A class is a blueprint for creating objects, defining their attributes and methods
  • An object is an of a class, representing a specific entity with its own set of attribute values
  • Attributes are variables that store data within a class or object
  • Methods are functions defined within a class that describe the behavior of objects
  • The constructor (usually
    [__init__](https://www.fiveableKeyTerm:__init__)
    in Python) is a special method that initializes a new object's attributes when it is created
  • Instances are individual objects created from a class, each with its own set of attribute values
  • occurs when a subclass provides a specific implementation for a method that is already defined in its superclass
  • An defines a set of abstract methods that a class must implement, ensuring a common structure for related classes

Key Terms to Review (34)

__init__: __init__ is a special method in Python that is automatically called when an object of a class is created. It is used to initialize the attributes of the object, setting them to their starting values.
@abstractmethod: @abstractmethod is a decorator in Python that is used to define an abstract method within an abstract base class. An abstract method is a method that has no implementation and must be overridden by any concrete subclasses of the abstract base class.
@property: @property is a built-in decorator in Python that allows you to define a method as a property, enabling you to access it like an attribute while still controlling access through getter, setter, and deleter methods. This feature helps to encapsulate data and provides a way to define custom behavior when getting or setting a value, promoting cleaner and more manageable code. By using @property, you can maintain the integrity of your data by applying validation rules or other logic when an attribute is accessed or modified.
ABC: ABC is a fundamental concept in programming that refers to the basic building blocks of object-oriented programming. It stands for Abstraction, Encapsulation, and Polymorphism, which are the three key principles that underlie the object-oriented paradigm. These principles enable programmers to create complex and modular software systems by breaking down problems into smaller, manageable components.
Abstraction: Abstraction is the process of simplifying complex systems or entities by focusing on their essential features and hiding unnecessary details. It allows programmers to manage complexity and create more modular, reusable, and maintainable code.
Attribute: An attribute is a characteristic or property of an object, class, or module in object-oriented programming. It is a variable that holds a value and is associated with a specific instance or class.
Class: A class is a blueprint for creating objects, encapsulating data for the object and methods to manipulate that data. It allows for the creation of user-defined data structures.
Class: In the context of programming, a class is a blueprint or template that defines the structure and behavior of objects. It serves as a blueprint for creating objects, which are instances of the class, and encapsulates data and functionality within a cohesive unit.
Class attribute: A class attribute is a variable that is shared among all instances of a class. It is defined within the class but outside any instance methods.
Dataclasses: Dataclasses are a Python feature introduced in version 3.7 that provide a way to create classes with minimal boilerplate code. They are designed to simplify the creation of data-focused classes by automatically generating common methods, such as '.__init__', '.__repr__', and '.__eq__', based on the class's fields.
Def: The 'def' keyword in Python is used to define a function, which is a reusable block of code that performs a specific task. Functions allow programmers to break down complex problems into smaller, more manageable parts, making the code more organized, efficient, and easier to maintain.
Dictionary: A dictionary in Python is a collection of key-value pairs where each key is unique. It allows for efficient data retrieval based on the keys.
Dictionary: A dictionary in Python is an unordered collection of key-value pairs, where each key is unique and is associated with a corresponding value. Dictionaries provide a flexible and efficient way to store and retrieve data, making them a fundamental data structure in the language.
Encapsulation: Encapsulation is a fundamental concept in object-oriented programming (OOP) that involves bundling data and methods into a single unit, known as a class. It is the mechanism that allows objects to hide their internal implementation details from the outside world, providing a well-defined interface for interacting with the object.
Factory: A factory is a facility where goods are manufactured or assembled through the use of machinery, tools, and labor. It serves as a centralized location for the production of various products, often on a large scale, to meet the demands of consumers or other businesses.
Hierarchical inheritance: Hierarchical inheritance is a type of inheritance in object-oriented programming where multiple derived classes inherit from a single base class. This allows for shared functionality and attributes to be defined in the base class and reused across multiple subclasses.
Inheritance: Inheritance is a fundamental concept in object-oriented programming where a new class is created based on an existing class, inheriting its attributes and behaviors. This allows for code reuse, hierarchical organization, and the creation of specialized classes that build upon the foundation of more general ones.
Instance: An instance is a specific realization or occurrence of a class or object in object-oriented programming. It represents a unique example or instantiation of a general concept or blueprint defined by the class.
Instance attribute: An instance attribute is a variable that is bound to an individual object of a class. It is unique to each instance and can hold different values for different instances.
Instance method: An instance method is a function defined inside a class that operates on instances of that class. It can access and modify the data attributes of the instance.
Int: The 'int' data type in Python represents whole numbers or integers, which are numbers without fractional parts. It is a fundamental data type that is used extensively in programming to store and manipulate numeric values.
Interface: An interface is a shared boundary across which two or more separate components of a system exchange information. It serves as the point of interaction and communication between different elements, allowing them to work together effectively.
List: A list in Python is an ordered collection of items, where each item can be of a different data type. Lists are one of the most fundamental and versatile data structures in the Python programming language, allowing you to store and manipulate multiple values in a single variable.
Method: A method is a function that is defined within a class or an object. It encapsulates a specific behavior or action that an object can perform, allowing it to interact with its data and other objects.
Object: An object is a fundamental concept in programming that represents a specific instance of a class, with its own unique data and behavior. It encapsulates both the state (attributes or properties) and the actions (methods) that define a particular entity or thing.
Object-oriented programming: Object-oriented programming (OOP) is a programming paradigm based on the concept of objects, which can contain data and code to manipulate that data. Python supports OOP, allowing for the creation and manipulation of classes and objects.
Overriding: Overriding is a feature in object-oriented programming that allows a subclass to provide a specific implementation of a method that is already defined in its superclass. This means that when a method is called on an object of the subclass, the version defined in the subclass is executed, effectively replacing the behavior of the superclass method. This concept promotes flexibility and code reusability by allowing subclasses to tailor inherited behaviors to better fit their specific needs.
Polymorphism: Polymorphism is a fundamental concept in object-oriented programming that allows objects of different classes to be treated as objects of a common superclass. It enables objects to take on multiple forms, allowing them to respond to the same method call in different ways.
Return: The term 'return' in programming refers to the action of a function or method sending a value back to the code that called it. It is a fundamental concept that allows functions to communicate with the rest of a program, providing useful output or results based on the input they receive.
Return statement: A return statement is used in a function to send a result back to the caller. It terminates the execution of the function and can optionally pass back an expression or value.
Self: The 'self' in programming refers to the instance of an object or class that the current method or function is operating on. It is a way for an object to refer to and access its own attributes and methods.
Singleton: The Singleton is a creational design pattern that restricts the instantiation of a class to one object, providing a global point of access to it. It ensures that a class has only one instance and provides a global point of access to it.
Str: The str (string) data type in Python is a collection of one or more characters that can include letters, digits, and various symbols. Strings are used to represent and manipulate textual data within a Python program.
Super(): The 'super()' function is a built-in function in Python that allows a subclass to call a method or access an attribute from its parent or superclass. It is a crucial tool in the context of object-oriented programming, as it enables the reuse of code and the implementation of inheritance hierarchies.
© 2024 Fiveable Inc. All rights reserved.
AP® and SAT® are trademarks registered by the College Board, which is not affiliated with, and does not endorse this website.
Glossary
Glossary