{ "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "provenance": [], "authorship_tag": "ABX9TyNCI/1TEHBptTavfxUtgKcG", "include_colab_link": true }, "kernelspec": { "name": "python3", "display_name": "Python 3" }, "language_info": { "name": "python" } }, "cells": [ { "cell_type": "markdown", "metadata": { "id": "view-in-github", "colab_type": "text" }, "source": [ "\"Open" ] }, { "cell_type": "markdown", "source": [ "# **Classes:**\n", "A class is a blueprint or a template for creating objects. It defines the common attributes (data) and methods (functions) that all objects of that class will possess. Think of a class as the design for a house – it specifies the number of rooms, the layout, etc., but it isn't an actual house." ], "metadata": { "id": "BBZ7KgAgTDoj" } }, { "cell_type": "code", "execution_count": 4, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "oGefoAfcS_qQ", "outputId": "386062a5-0214-474f-b7a9-79b4c3833fd3" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Buddy is a Canis familiaris.\n", "Lucy is 5 years old.\n", "Buddy says Woof!\n", "Ozzy is 2 year(s) old.\n", "Skippy is 12 year(s) old.\n", "Filou is 8 year(s) old.\n", "2\n", "bark\n", "Buddy\n", "Canine\n", "Buddy is barking!\n", "Buddy is 3 years old.\n", "Charlie is 5 years old.\n", "Canine\n", "Buddy\n", "Charlie\n", "Max\n", "Feline\n", "Feline\n" ] } ], "source": [ "class ClassName:\n", " # Class attributes (shared by all instances)\n", " class_attribute = \"value\"\n", "\n", " # Constructor method (for initializing object attributes)\n", " def __init__(self, param1, param2):\n", " self.param1 = param1 # Instance attribute\n", " self.param2 = param2 # Instance attribute\n", "\n", " # Instance method\n", " def method_name(self):\n", " return f\"This is a method of {self.param1}\"\n", "\n", "class Dog:\n", " species = \"Canis familiaris\" # Class attribute\n", "\n", " def __init__(self, name, age):\n", " self.name = name # Instance attribute\n", " self.age = age # Instance attribute\n", "\n", " def bark(self):\n", " return f\"{self.name} says Woof!\"\n", "\n", "# Create objects (instances) of the Dog class\n", "dog1 = Dog(\"Buddy\", 3)\n", "dog2 = Dog(\"Lucy\", 5)\n", "\n", "# Access attributes\n", "print(f\"{dog1.name} is a {dog1.species}.\")\n", "print(f\"{dog2.name} is {dog2.age} years old.\")\n", "\n", "# Call methods\n", "print(dog1.bark())\n", "\n", "class Dog:\n", "\n", " def __init__(self, name, age):\n", " self.name = name\n", " self.age = age\n", "\n", " def bark(self):\n", " print(\"bark bark!\")\n", "\n", "class Dog:\n", "\n", " def __init__(self, name, age):\n", " self.name = name\n", " self.age = age\n", "\n", " def bark(self):\n", " print(\"bark bark!\")\n", "\n", " def doginfo(self):\n", " print(self.name + \" is \" + str(self.age) + \" year(s) old.\")\n", "\n", "ozzy = Dog(\"Ozzy\", 2)\n", "skippy = Dog(\"Skippy\", 12)\n", "filou = Dog(\"Filou\", 8)\n", "\n", "ozzy.doginfo()\n", "skippy.doginfo()\n", "filou.doginfo()\n", "\n", "class Dog:\n", "\n", " def __init__(self, name, age):\n", " self.name = name\n", " self.age = age\n", "\n", " def bark(self):\n", " print(\"bark bark!\")\n", "\n", " def doginfo(self):\n", " print(self.name + \" is \" + str(self.age) + \" year(s) old.\")\n", "\n", " def birthday(self):\n", " self.age +=1\n", "\n", "ozzy = Dog(\"Ozzy\", 2)\n", "\n", "print(ozzy.age)\n", "\n", "class Dog:\n", "\n", " def __init__(self, name, age):\n", " self.name = name\n", " self.age = age\n", "\n", " def bark(self):\n", " print(\"bark bark!\")\n", "\n", " def doginfo(self):\n", " print(self.name + \" is \" + str(self.age) + \" year(s) old.\")\n", "\n", " def birthday(self):\n", " self.age +=1\n", "\n", " def setBuddy(self, buddy):\n", " self.buddy = buddy\n", " buddy.buddy = self\n", "\n", "ozzy = Dog(\"Ozzy\", 2)\n", "filou = Dog(\"Filou\", 8)\n", "\n", "ozzy.setBuddy(filou)\n", "'''\n", "# Initialize\n", "short_window = 40\n", "long_window = 100\n", "signals = pd.DataFrame(index=aapl.index)\n", "signals['signal'] = 0.0\n", "\n", "# Create short simple moving average over the short window\n", "signals['short_mavg'] = aapl['Close'].rolling(window=short_window, min_periods=1, center=False).mean()\n", "\n", "# Create long simple moving average over the long window\n", "signals['long_mavg'] = aapl['Close'].rolling(window=long_window, min_periods=1, center=False).mean()\n", "\n", "# Create signals\n", "signals['signal'][short_window:] = np.where(signals['short_mavg'][short_window:] > signals['long_mavg'][short_window:], 1.0, 0.0)\n", "\n", "# Generate trading orders\n", "signals['positions'] = signals['signal'].diff()\n", "\n", "# Print `signals`\n", "print(signals)\n", "\n", "class MovingAverage():\n", "\n", " def __init__(self, symbol, bars, short_window, long_window):\n", " self.symbol = symbol\n", " self.bars = bars\n", " self.short_window = short_window\n", " self.long_window = long_window\n", "\n", " def generate_signals(self):\n", " signals = pd.DataFrame(index=self.bars.index)\n", " signals['signal'] = 0.0\n", "\n", " signals['short_mavg'] = bars['Close'].rolling(window=self.short_window, min_periods=1, center=False).mean()\n", " signals['long_mavg'] = bars['Close'].rolling(window=self.long_window, min_periods=1, center=False).mean()\n", "\n", " signals['signal'][self.short_window:] = np.where(signals['short_mavg'][self.short_window:] > signals['long_mavg'][self.short_window:], 1.0, 0.0)\n", "\n", " signals['positions'] = signals['signal'].diff()\n", "\n", " return signals\n", "\n", "apple = MovingAverage('aapl', aapl, 40, 100)\n", "print(apple.generate_signals())\n", "\n", "microsoft = MovingAverage('msft', msft, 40, 100)\n", "print(microsoft.generate_signals())\n", "'''\n", "class Dog:\n", " sound = \"bark\"\n", "\n", "dog1 = Dog() # Creating object from class\n", "print(dog1.sound) # Accessing the class\n", "\n", "class Dog:\n", " species = \"Canine\" # Class attribute\n", "\n", " def __init__(self, name, age):\n", " self.name = name # Instance attribute\n", " self.age = age # Instance attribute\n", "\n", "class Dog:\n", " species = \"Canine\" # Class attribute\n", "\n", " def __init__(self, name, age):\n", " self.name = name # Instance attribute\n", " self.age = age # Instance attribute\n", "\n", "# Creating an object of the Dog class\n", "dog1 = Dog(\"Buddy\", 3)\n", "\n", "print(dog1.name)\n", "print(dog1.species)\n", "\n", "class Dog:\n", " def __init__(self, name, age):\n", " self.name = name\n", " self.age = age\n", "\n", " def bark(self):\n", " print(f\"{self.name} is barking!\")\n", "\n", "# Creating an instance of Dog\n", "dog1 = Dog(\"Buddy\", 3)\n", "dog1.bark()\n", "\n", "class Dog:\n", " def __init__(self, name, age):\n", " self.name = name\n", " self.age = age\n", "\n", " def __str__(self):\n", " return f\"{self.name} is {self.age} years old.\"\n", "dog1 = Dog(\"Buddy\", 3)\n", "dog2 = Dog(\"Charlie\", 5)\n", "\n", "print(dog1)\n", "print(dog2)\n", "\n", "class Dog:\n", " # Class variable\n", " species = \"Canine\"\n", "\n", " def __init__(self, name, age):\n", " # Instance variables\n", " self.name = name\n", " self.age = age\n", "\n", "# Create objects\n", "dog1 = Dog(\"Buddy\", 3)\n", "dog2 = Dog(\"Charlie\", 5)\n", "\n", "# Access class and instance variables\n", "print(dog1.species) # (Class variable)\n", "print(dog1.name) # (Instance variable)\n", "print(dog2.name) # (Instance variable)\n", "\n", "# Modify instance variables\n", "dog1.name = \"Max\"\n", "print(dog1.name) # (Updated instance variable)\n", "\n", "# Modify class variable\n", "Dog.species = \"Feline\"\n", "print(dog1.species) # (Updated class variable)\n", "print(dog2.species)\n", "\n" ] }, { "cell_type": "markdown", "source": [ "# **Objects:**\n", "An object is an instance of a class. When you create an object from a class, you are essentially building a \"house\" based on the \"blueprint.\" Each object has its own unique set of instance attributes, but they all share the class attributes and methods defined in their class." ], "metadata": { "id": "KR0JXL3oTEUa" } }, { "cell_type": "code", "source": [ "class Dog:\n", " def __init__(self, name, age):\n", " self._name = name # Conventionally private variable\n", " self._age = age # Conventionally private variable\n", "\n", " @property\n", " def name(self):\n", " return self._name # Getter\n", "\n", " @name.setter\n", " def name(self, value):\n", " self._name = value # Setter\n", "\n", " @property\n", " def age(self):\n", " return self._age # Getter\n", "\n", " @age.setter\n", " def age(self, value):\n", " if value < 0:\n", " print(\"Age cannot be negative!\")\n", " else:\n", " self._age = value # Setter\n", "\n", "class Animal:\n", " def sound(self):\n", " print(\"Some sound\")\n", "\n", "class Dog(Animal):\n", " def sound(self): # Method overriding\n", " print(\"Woof\")\n", "\n", "dog = Dog()\n", "dog.sound()\n", "\n", "\n", "class Dog:\n", " @staticmethod\n", " def info():\n", " print(\"Dogs are loyal animals.\")\n", "\n", " @classmethod\n", " def count(cls):\n", " print(\"There are many dogs of class\", cls)\n", "\n", "dog = Dog()\n", "dog.info() # Static method call\n", "dog.count() # Class method call\n", "\n", "from abc import ABC, abstractmethod\n", "class Animal(ABC):\n", " @abstractmethod\n", " def sound(self):\n", " pass\n", "\n", "class Dog(Animal):\n", " def sound(self):\n", " print(\"Woof\")\n", "\n", "dog = Dog()\n", "dog.sound()\n", "\n", "class Dog:\n", " species = \"Canine\" # Class variable\n", "\n", " def __init__(self, name, age):\n", " self.name = name # Instance variable\n", " self.age = age # Instance variable\n", "\n", "dog1 = Dog(\"Buddy\", 3)\n", "dog2 = Dog(\"Lucy\", 2)\n", "\n", "print(dog1.species) # Accessing class variable\n", "print(dog2.name) # Accessing instance variable\n", "\n", "# create class\n", "class Bike:\n", " name = \"\"\n", " gear = 0\n", "\n", "# create objects of class\n", "bike1 = Bike()\n", "\n", "# define a class\n", "class Bike:\n", " name = \"\"\n", " gear = 0\n", "\n", "# create object of class\n", "bike1 = Bike()\n", "\n", "# access attributes and assign new values\n", "bike1.gear = 11\n", "bike1.name = \"Mountain Bike\"\n", "\n", "print(f\"Name: {bike1.name}, Gears: {bike1.gear} \")\n", "\n", "# define a class\n", "class Employee:\n", " # define a property\n", " employee_id = 0\n", "\n", "# create two objects of the Employee class\n", "employee1 = Employee()\n", "employee2 = Employee()\n", "\n", "# access property using employee1\n", "employee1.employeeID = 1001\n", "print(f\"Employee ID: {employee1.employeeID}\")\n", "\n", "# access properties using employee2\n", "employee2.employeeID = 1002\n", "print(f\"Employee ID: {employee2.employeeID}\")\n", "\n", "# create a class\n", "class Room:\n", " length = 0.0\n", " breadth = 0.0\n", "\n", " # method to calculate area\n", " def calculate_area(self):\n", " print(\"Area of Room =\", self.length * self.breadth)\n", "\n", "# create object of Room class\n", "study_room = Room()\n", "\n", "# assign values to all the properties\n", "study_room.length = 42.5\n", "study_room.breadth = 30.8\n", "\n", "# access method inside class\n", "study_room.calculate_area()\n", "\n", "class Employee:\n", " 'Common base class for all employees'\n", " empCount = 0\n", "\n", " def __init__(self, name, salary):\n", " self.name = name\n", " self.salary = salary\n", " Employee.empCount += 1\n", "\n", " def displayCount(self):\n", " print(\"Total Employee %d\" % Employee.empCount)\n", "\n", " def displayEmployee(self):\n", " print(\"Name : \", self.name, \", Salary: \", self.salary)\n", "\n", " # This would create first object of Employee class\n", "emp1 = Employee(\"Zara\", 2000)\n", "# This would create second object of Employee class\n", "emp2 = Employee(\"Manni\", 5000)\n", "\n", "class Employee:\n", " \"Common base class for all employees\"\n", " empCount = 0\n", "\n", " def __init__(self, name, salary):\n", " self.name = name\n", " self.salary = salary\n", " Employee.empCount += 1\n", "\n", " def displayCount(self):\n", " print (\"Total Employee %d\" % Employee.empCount)\n", "\n", " def displayEmployee(self):\n", " print (\"Name : \", self.name, \", Salary: \", self.salary)\n", "\n", "# This would create first object of Employee class\n", "emp1 = Employee(\"Zara\", 2000)\n", "# This would create second object of Employee class\n", "emp2 = Employee(\"Manni\", 5000)\n", "emp1.displayEmployee()\n", "emp2.displayEmployee()\n", "print (\"Total Employee %d\" % Employee.empCount)\n", "\n", "class Employee:\n", " 'Common base class for all employees'\n", " empCount = 0\n", "\n", " def __init__(self, name, salary):\n", " self.name = name\n", " self.salary = salary\n", " Employee.empCount += 1\n", "\n", " def displayCount(self):\n", " print (\"Total Employee %d\" % Employee.empCount)\n", "\n", " def displayEmployee(self):\n", " print (\"Name : \", self.name, \", Salary: \", self.salary)\n", "\n", "print (\"Employee.__doc__:\", Employee.__doc__)\n", "print (\"Employee.__name__:\", Employee.__name__)\n", "print (\"Employee.__module__:\", Employee.__module__)\n", "print (\"Employee.__bases__:\", Employee.__bases__)\n", "print (\"Employee.__dict__:\", Employee.__dict__)\n", "\n", "\n" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "JdFBFJRCTEdK", "outputId": "44922fef-23bf-47c0-c22d-0614b2a25322" }, "execution_count": 5, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Woof\n", "Dogs are loyal animals.\n", "There are many dogs of class \n", "Woof\n", "Canine\n", "Lucy\n", "Name: Mountain Bike, Gears: 11 \n", "Employee ID: 1001\n", "Employee ID: 1002\n", "Area of Room = 1309.0\n", "Name : Zara , Salary: 2000\n", "Name : Manni , Salary: 5000\n", "Total Employee 2\n", "Employee.__doc__: Common base class for all employees\n", "Employee.__name__: Employee\n", "Employee.__module__: __main__\n", "Employee.__bases__: (,)\n", "Employee.__dict__: {'__module__': '__main__', '__doc__': 'Common base class for all employees', 'empCount': 0, '__init__': , 'displayCount': , 'displayEmployee': , '__dict__': , '__weakref__': }\n" ] } ] }, { "cell_type": "markdown", "source": [ "# **Key Concepts:**\n", "Attributes: These are variables that store data associated with a class or an object.\n", "Class attributes: Shared by all instances of the class.\n", "Instance attributes: Unique to each object (instance) of the class.\n", "Methods: These are functions defined within a class that operate on the object's data. They define the behavior of the objects.\n", "self: A special parameter in instance methods that refers to the instance of the class itself. It's used to access instance attributes and other instance methods.\n", "__init__ method (Constructor): A special method called automatically when a new object is created. It's used to initialize the instance attributes of the object." ], "metadata": { "id": "My5za46TTEmi" } }, { "cell_type": "code", "source": [ "num = 20\n", "print (type(num))\n", "num1 = 55.50\n", "print (type(num1))\n", "s = \"TutorialsPoint\"\n", "print (type(s))\n", "dct = {'a':1,'b':2,'c':3}\n", "print (type(dct))\n", "def SayHello():\n", " print (\"Hello World\")\n", " return\n", "print (type(SayHello))\n", "\n", "\n", "class Point:\n", " def __init__( self, x=0, y=0):\n", " self.x = x\n", " self.y = y\n", " def __del__(self):\n", " class_name = self.__class__.__name__\n", " print (class_name, \"destroyed\")\n", "\n", "pt1 = Point()\n", "pt2 = pt1\n", "pt3 = pt1\n", "# prints the ids of the obejcts\n", "print (id(pt1), id(pt2), id(pt3))\n", "'''\n", "class JustCounter:\n", " secretCount = 0\n", "\n", " def count(self):\n", " self.countsecretCount += 1\n", " print(self.secretCount)\n", "\n", "counter = JustCounter()\n", "counter.count()\n", "print(counter.secretCount)\n", "'''\n", "class Employee:\n", " name = \"Bhavesh Aggarwal\"\n", " age = \"30\"\n", "\n", "# instance of the class\n", "emp = Employee()\n", "# accessing class attributes\n", "print(\"Name of the Employee:\", emp.name)\n", "print(\"Age of the Employee:\", emp.age)\n", "\n", "class Employee:\n", " # class attribute\n", " empCount = 0\n", " def __init__(self, name, age):\n", " self.__name = name\n", " self.__age = age\n", " # modifying class attribute\n", " Employee.empCount += 1\n", " print (\"Name:\", self.__name, \", Age: \", self.__age)\n", " # accessing class attribute\n", " print (\"Employee Count:\", Employee.empCount)\n", "\n", "e1 = Employee(\"Bhavana\", 24)\n", "print()\n", "e2 = Employee(\"Rajesh\", 26)\n", "\n", "class Employee:\n", " def __init__(self, name=\"Bhavana\", age=24):\n", " self.name = name\n", " self.age = age\n", " def displayEmployee(self):\n", " print (\"Name : \", self.name, \", age: \", self.age)\n", "\n", "print (\"Employee.__doc__:\", Employee.__doc__)\n", "print (\"Employee.__name__:\", Employee.__name__)\n", "print (\"Employee.__module__:\", Employee.__module__)\n", "print (\"Employee.__bases__:\", Employee.__bases__)\n", "print (\"Employee.__dict__:\", Employee.__dict__ )\n", "\n", "\n", "class Student:\n", " def __init__(self, name, grade):\n", " self.__name = name\n", " self.__grade = grade\n", " print (\"Name:\", self.__name, \", Grade:\", self.__grade)\n", "\n", "# Creating instances\n", "student1 = Student(\"Ram\", \"B\")\n", "student2 = Student(\"Shyam\", \"C\")\n", "\n", "class Employee:\n", " empCount = 0\n", " def __init__(self, name, age):\n", " self.__name = name\n", " self.__age = age\n", " Employee.empCount += 1\n", " def showcount(self):\n", " print (self.empCount)\n", "\n", " counter = classmethod(showcount)\n", "\n", "e1 = Employee(\"Bhavana\", 24)\n", "e2 = Employee(\"Rajesh\", 26)\n", "e3 = Employee(\"John\", 27)\n", "\n", "e1.showcount()\n", "Employee.counter()\n", "\n", "\n", "class Employee:\n", " empCount = 0\n", " def __init__(self, name, age):\n", " self.name = name\n", " self.age = age\n", " Employee.empCount += 1\n", "\n", " @classmethod\n", " def showcount(cls):\n", " print (cls.empCount)\n", "\n", " @classmethod\n", " def newemployee(cls, name, age):\n", " return cls(name, age)\n", "\n", "e1 = Employee(\"Bhavana\", 24)\n", "e2 = Employee(\"Rajesh\", 26)\n", "e3 = Employee(\"John\", 27)\n", "e4 = Employee.newemployee(\"Anil\", 21)\n", "\n", "Employee.showcount()\n", "\n", "class Cloth:\n", " # Class attribute\n", " price = 4000\n", "\n", " @classmethod\n", " def showPrice(cls):\n", " return cls.price\n", "\n", "# Accessing class attribute\n", "print(Cloth.showPrice())\n", "\n", "class Cloth:\n", " pass\n", "\n", "# class method\n", "@classmethod\n", "def brandName(cls):\n", " print(\"Name of the brand is Raymond\")\n", "\n", "# adding dynamically\n", "setattr(Cloth, \"brand_name\", brandName)\n", "newObj = Cloth()\n", "newObj.brand_name()\n", "\n", "class Cloth:\n", " # class method\n", " @classmethod\n", " def brandName(cls):\n", " print(\"Name of the brand is Raymond\")\n", "\n", "# deleting dynamically\n", "del Cloth.brandName\n", "print(\"Method deleted\")\n", "\n", "class Employee:\n", " empCount = 0\n", " def __init__(self, name, age):\n", " self.__name = name\n", " self.__age = age\n", " Employee.empCount += 1\n", "\n", " # creating staticmethod\n", " def showcount():\n", " print (Employee.empCount)\n", " return\n", " counter = staticmethod(showcount)\n", "\n", "e1 = Employee(\"Bhavana\", 24)\n", "e2 = Employee(\"Rajesh\", 26)\n", "e3 = Employee(\"John\", 27)\n", "\n", "e1.counter()\n", "Employee.counter()\n", "\n", "class Student:\n", " stdCount = 0\n", " def __init__(self, name, age):\n", " self.__name = name\n", " self.__age = age\n", " Student.stdCount += 1\n", "\n", " # creating staticmethod\n", " @staticmethod\n", " def showcount():\n", " print (Student.stdCount)\n", "\n", "e1 = Student(\"Bhavana\", 24)\n", "e2 = Student(\"Rajesh\", 26)\n", "e3 = Student(\"John\", 27)\n", "\n", "print(\"Number of Students:\")\n", "Student.showcount()\n" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "UvGvhDxYTEt6", "outputId": "c7788470-1185-49ef-aa29-35660cf00c08" }, "execution_count": 9, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "\n", "\n", "\n", "\n", "\n", "Point destroyed\n", "140548579305584 140548579305584 140548579305584\n", "Name of the Employee: Bhavesh Aggarwal\n", "Age of the Employee: 30\n", "Name: Bhavana , Age: 24\n", "Employee Count: 1\n", "\n", "Name: Rajesh , Age: 26\n", "Employee Count: 2\n", "Employee.__doc__: None\n", "Employee.__name__: Employee\n", "Employee.__module__: __main__\n", "Employee.__bases__: (,)\n", "Employee.__dict__: {'__module__': '__main__', '__init__': , 'displayEmployee': , '__dict__': , '__weakref__': , '__doc__': None}\n", "Name: Ram , Grade: B\n", "Name: Shyam , Grade: C\n", "3\n", "3\n", "4\n", "4000\n", "Name of the brand is Raymond\n", "Method deleted\n", "3\n", "3\n", "Number of Students:\n", "3\n" ] } ] }, { "cell_type": "markdown", "source": [ "# **OOP: Introduction**\n", "Object-oriented programming has some advantages over other design patterns. Development is faster and cheaper, with better software maintainability. This, in turn, leads to higher-quality software, which is also extensible with new methods and attributes. The learning curve is, however, steeper. The concept may be too complex for beginners. Computationally, OOP software is slower, and uses more memory since more lines of code have to be written." ], "metadata": { "id": "76b1KNzuTE1q" } } ] }