{"id":25005193,"url":"https://github.com/foyez/oop","last_synced_at":"2025-04-12T14:24:39.030Z","repository":{"id":116062211,"uuid":"165189835","full_name":"foyez/oop","owner":"foyez","description":"Basic concepts of object oriented programming","archived":false,"fork":false,"pushed_at":"2024-10-30T21:15:28.000Z","size":49,"stargazers_count":5,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-04-12T14:24:35.052Z","etag":null,"topics":["object-oriented-programming","oop","programming-paradigms"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/foyez.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-01-11T06:15:26.000Z","updated_at":"2024-10-30T21:15:32.000Z","dependencies_parsed_at":null,"dependency_job_id":"027e5028-91af-4ee2-953e-31bb1f7fc321","html_url":"https://github.com/foyez/oop","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/foyez%2Foop","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/foyez%2Foop/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/foyez%2Foop/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/foyez%2Foop/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/foyez","download_url":"https://codeload.github.com/foyez/oop/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248579130,"owners_count":21127762,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["object-oriented-programming","oop","programming-paradigms"],"created_at":"2025-02-05T00:30:02.655Z","updated_at":"2025-04-12T14:24:39.009Z","avatar_url":"https://github.com/foyez.png","language":"Python","readme":"# Object Oriented Programming\n\n## What is OOP?\nObject oriented programming is a method of programming that attempts to model some process or thing in the world as a **class** or **object**.\n\n## Class\n\n\u003cdetails\u003e\n\u003csummary\u003eView contents\u003c/summary\u003e\n\n**Class:** - A blueprint for objects. Classes can contain methods (functions) and attributes (simmilar to keys in a object or dict).\n\n### Instance\n\n**Instance:** - Objects that are constructed from a class blueprint that contain their class's methods and properties.\n\n**Instantiating:** Creating an object that is an instance of a class is called instantiating a class.\n\n### Creating a Class\n\n**In Python:**\n\n```py\n\n# vehicle.py\n# _name - private variable or private property or method\n# __name - \n\nclass Vehicle:\n  def __init__(self, make, model, year):\n    self.make = make\n    self.model = model\n    self.year = year\n\ncar = Vehicle('Audi', '45d', 2018)\n\n```\n\n`Classes in Python can have a special __init__ method, which gets called every time you create an instance of the class (instantiate). The self keyword refers to the current class instance.`\n\n**In Javascript:**\n\n```js\n\nclass Vehicle {\n  constructor(make, model, year) {\n    this.make = make\n    this.model = model\n    this.year = year\n  }\n}\n\ncar = new Vehicle('Audi', '45d', 2018)\n\n```\n  \n\u003c/details\u003e\n\n## Why OOP?\n\nWith object oriented programming, the goal is to *encapsulate* your code into **logical, hierarchical groupings using classes** so that you can reason about your code at higher level.\n\n## 4 fundamental concepts of OOP\n\n1. Abstraction\n2. Encapsulation\n3. Inheritance\n4. Polymorphism\n\n## 1. Abstraction\n\n\u003cdetails\u003e\n\u003csummary\u003eView contents\u003c/summary\u003e\n\n**Abstraction:** - Abstraction captures the essential attributes and behavior based on the context, while ignores the irrelvent information.\n\nFor example, the essential attributes and behavior for a student from the perspective of academic:\n\nAttributes: (Course Name, Grade, Student ID, etc.)\nBehavior: (Studying, Doing Assignments, Attending Lectures, etc.)\n\nBut the hobby of a student or the favorite sports of a student is not important here.\n  \n\u003c/details\u003e\n\n## 2. Encapsulation\n\n\u003cdetails\u003e\n\u003csummary\u003eView contents\u003c/summary\u003e\n\n**Encapsulation** - Encapsulation means a sort capsule that contains something inside, some of which can be accessed from outside and some of which cannot. In programming, encapsulation means the practice of keeping fields within a class private, then providing access to those fields via public methods (e.g. getter and setter methods).\n\n**Example:** \n* Let designing a Deck class, we make cards a private attribute (a list)\n* The length of the cards should be accessed via a public method called count() --i.e. Deck.count()\n  \n\u003c/details\u003e\n\n## 3. Inheritance\n\n\u003cdetails\u003e\n\u003csummary\u003eView contents\u003c/summary\u003e\n\n**Inheritance:** A key feature of OOP is the ability to define a class which inherits from another class (a \"base\" or \"parent\" class).\n\n**Example:**\n\n**In Python:**\n\n```py\nclass User:\n    active_users = 0\n\n    def __init__(self, first_name: str, last_name: str, age: int = 18):\n        self._first_name = first_name  # instance variable\n        self._last_name = last_name  # instance variable\n        self.__age = age\n\n    def __repr__(self):\n        return f\"{self._first_name} is {self.__age}.\"\n        \n    # def __str__(self):\n    #     return f\"{self._first_name} is {self.__age}.\"\n\n    @property\n    def full_name(self):\n        return f\"{self._first_name} {self._last_name}\"\n\n    @full_name.setter\n    def full_name(self, name):\n        self._first_name, self._last_name = name.split(' ')\n\n    @classmethod\n    def display_active_users(cls):\n        return f\"There are currently {cls.active_users} active users\"\n\n    def description(self):\n        return f\"{self._first_name} is a general user.\"\n\n    def birthday(self):\n        self.__age += 1\n        return f\"Happy {self.__age}th, {self._first_name}\"\n\n    def login(self):\n        User.active_users += 1\n\n    def logout(self):\n        User.active_users -= 1\n        return f\"{self._first_name} has logged out\"\n\n\nclass Moderator(User):\n    def __init__(self, first_name, last_name, community):\n        super().__init__(first_name, last_name)\n        self.__community = community\n\n    # override method\n    def description(self):\n        return f\"{self._first_name} is a moderator.\"\n\n    def remove_post(self):\n        return f\"{self.full_name} removed a post from the {self.__community} community\"\n\n\ngeneralUser = User('Foyez', 'Ahmed')\nmoderator = Moderator('Sohel', 'Mahmud', 'cricket')\n\nprint(generalUser)\n\nprint(generalUser.__dict__)\nprint(moderator.__dict__)\nprint()\n\nprint(generalUser.full_name)\n\ngeneralUser.full_name = 'Manam Ahmed'\nprint(generalUser.full_name)\nprint()\n\nprint(generalUser.description())\nprint(moderator.description())\nprint()\n\ngeneralUser.login()\nprint(User.display_active_users())\n\nprint(moderator.remove_post())\n```\n\n**In Javascript:**\n\n```js\n// Class syntax or syntactical sugar\n// myPerson --\u003e Person.prototype --\u003e Object.prototype --\u003e null\n\nconst activeUsers = Symbol('activeUsers')\n\nclass User {\n  constructor(firstName, lastName, age = 18) {\n    User[activeUsers] = 0\n    this._firstName = firstName // instance variable\n    this._lastName = lastName\n    this._age = age\n  }\n\n  get fullName() {\n    return `${this._firstName} ${this._lastName}`\n  }\n\n  set fullName(name) {\n    ;[this._firstName, this._lastName] = name.split(' ')\n  }\n\n  static display_active_users() {\n    return `There are currently ${User[activeUsers]} active users`\n  }\n\n  description() {\n    return `${this._firstName} is a general user.`\n  }\n\n  birthday() {\n    this._age += 1\n    return `Happy ${this._age}th, ${this._firstName}`\n  }\n\n  login() {\n    User[activeUsers] += 1\n  }\n\n  logout() {\n    User[activeUsers] -= 1\n    return `${this._firstName} has logged out`\n  }\n}\n\nclass Moderator extends User {\n  // js isn't strict about arity\n  constructor(firstName, community) {\n    super(firstName)\n    this._community = community\n  }\n\n  // override method\n  description() {\n    return `${this._firstName} is a moderator.`\n  }\n\n  remove_post() {\n    return `${this.fullName} removed a post from the ${this._community} community`\n  }\n}\n\ngeneralUser = new User('Foyez', 'Ahmed', 20)\nmoderator = new Moderator('Sohel', 'cricket')\n\nconsole.log(generalUser.fullName)\n\ngeneralUser.fullName = 'Manam Ahmed'\nconsole.log(generalUser.fullName)\nconsole.log()\n\nconsole.log(generalUser.description())\nconsole.log(moderator.description())\nconsole.log()\n\nconsole.log(generalUser.birthday())\nconsole.log(moderator.birthday())\nconsole.log()\n\ngeneralUser.login()\nconsole.log(User.display_active_users())\n\nconsole.log(moderator.remove_post())\n```\n\n\u003c/details\u003e\n\n## 4. Polymorphism\n\n\u003cdetails\u003e\n\u003csummary\u003eView contents\u003c/summary\u003e\n\n**Polymorphism:** The ability of an object to have different or many (poly) forms (morph) depending on the context.\n\n**Example 1: The same class method works in a similar way for different classes**\n\n```py\nCat.speak() # meow\nDog.speak() # woof\nHuman.speak() # yo\n```\n\nAt a high level the `speak()` method doing the same thing, but at a low level the implementation of the method is totally different.\n\n**Example 2: The operation works for different kinds of objects**\n\n```py\nsample_list = [1, 2, 3]\nsample_tuple = (1, 2, 3)\nsample_string = 'awesome'\n\nlen(sample_list)\nlen(sample_tuple)\nlen(sample_string)\n```\n\n## Polymorphism \u0026 Inheritance\n\n**1. The same class method works in a similar way for different classes**\nA common implementation of this is to have a method in a base (or parent) class that is overriden by a subclass. This is called method **overridening**.\nThe same class method means that it have the same method signature (same name, same arguments \u0026 same return types).\n\n* Each subclass will have a different implementation of the method.\n* If the method is not implemented in the subclass, the version in the parent class is called instead.\n\n```py\nclass Animal():\n  def speak(self):\n    raise NotImplementedError('Subclass needs to implement this method')\n\nclass Dog(Animal):\n  def speak(self):\n    return 'woof'\n\nclass Cat(Animal):\n  def speak(self):\n    return 'meow'\n\nclass Fish(Animal):\n  pass\n\nd = Dog()\nprint(d.speak())\n\nf = Fish()\nprint(f.speak())\n```\n\n**2. (Polymorphism) The same operation works for different kinds of objects**\n\n```py\n8 + 2 # 10\n'8' + '2' # 82\n```\n  \n\u003c/details\u003e\n\n## References\n\n1. [What Are OOP Concepts?](https://stackify.com/oops-concepts-in-java/)\n2. [How to Use Object-Oriented Programming in Python – Key OOP Concepts and Interview Questions for Beginners](https://www.freecodecamp.org/news/object-oriented-programming-in-python-interview-questions/)\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffoyez%2Foop","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffoyez%2Foop","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffoyez%2Foop/lists"}