{ "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "provenance": [], "authorship_tag": "ABX9TyMQ3n5OEWGhT5W2WF/DqNkr", "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 and Objects**\n", "Objects are an encapsulation of variables and functions into a single entity. Objects get their variables and functions from classes. Classes are essentially a template to create your objects." ], "metadata": { "id": "0ixsQJ3ThNQj" } }, { "cell_type": "code", "execution_count": 2, "metadata": { "id": "NGjWrnZRhCvj", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "4c170fca-3393-44e3-e7ac-60b45cc5080e" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Buddy\n", "5\n", "4\n", "Buddy says woof!\n", "Max says woof!\n", "2020 Toyota Camry\n", "2018 Honda Accord\n", "2021 Ford Mustang\n", "Tom 6\n", "Mim 6\n", "Mim sound\n", "Mim is eating\n", "Tom sound\n", "Tom is eating\n", "Buddy says woof!\n", "3\n", "4\n", "Canis familiaris\n", "True\n", "False\n", "blah\n", "blah\n", "yackity\n", "This is a message inside the class.\n", "7\n", "Fer is a red convertible worth $60000.00.\n", "Jump is a blue van worth $10000.00.\n" ] } ], "source": [ "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} says woof!\")\n", "\n", "# Creating objects\n", "dog1 = Dog(\"Buddy\", 3)\n", "dog2 = Dog(\"Max\", 5)\n", "\n", "# Accessing attributes\n", "print(dog1.name)\n", "print(dog2.age)\n", "\n", "# Modifying attributes\n", "dog1.age = 4\n", "print(dog1.age)\n", "\n", "# Calling methods\n", "dog1.bark()\n", "dog2.bark()\n", "\n", "class Car:\n", " def __init__(self, make, model, year):\n", " self.make = make\n", " self.model = model\n", " self.year = year\n", "\n", " def display_info(self):\n", " print(f\"{self.year} {self.make} {self.model}\")\n", "\n", "# Creating multiple objects of the Car class\n", "car1 = Car(\"Toyota\", \"Camry\", 2020)\n", "car2 = Car(\"Honda\", \"Accord\", 2018)\n", "car3 = Car(\"Ford\", \"Mustang\", 2021)\n", "\n", "# Creating a list of Car objects\n", "cars = [car1, car2, car3]\n", "\n", "# Iterating over the list to access each Car object\n", "for car in cars:\n", " car.display_info()\n", "\n", "\n", "class Animal:\n", "\n", "\n", " def __init__(self, name, age):\n", " self.name = name # Instance attribute\n", " self.age = age # Instance attribute\n", "\n", " def speak(self):\n", " print(f\"{self.name} sound\")\n", "\n", " def eat(self):\n", " print(f\"{self.name} is eating\")\n", "\n", "\n", "\n", "cat=Animal(\"Tom\",6)\n", "dog=Animal(\"Mim\",6)\n", "\n", "print(f\"{cat.name} {cat.age}\")\n", "print(f\"{dog.name} {dog.age}\" )\n", "dog.speak()\n", "dog.eat()\n", "cat.speak()\n", "cat.eat()\n", "\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} says woof!\")\n", "\n", " def get_age(self):\n", " return self.age\n", "\n", " def set_age(self, age):\n", " self.age = age\n", "\n", "# Creating an object\n", "dog1 = Dog(\"Buddy\", 3)\n", "\n", "# Calling instance methods\n", "dog1.bark()\n", "print(dog1.get_age())\n", "\n", "# Modifying an attribute using a method\n", "dog1.set_age(4)\n", "print(dog1.get_age())\n", "\n", "class Dog:\n", " species = \"Canis familiaris\"\n", "\n", " def __init__(self, name, age):\n", " self.name = name\n", " self.age = age\n", "\n", " @classmethod\n", " def get_species(cls):\n", " return cls.species\n", "\n", "# Calling class method\n", "print(Dog.get_species())\n", "\n", "class Dog:\n", " def __init__(self, name, age):\n", " self.name = name\n", " self.age = age\n", "\n", " @staticmethod\n", " def is_puppy(age):\n", " return age < 1\n", "\n", "# Calling static method\n", "print(Dog.is_puppy(0.5))\n", "print(Dog.is_puppy(2))\n", "\n", "class MyClass:\n", " variable = \"blah\"\n", "\n", " def function(self):\n", " print(\"This is a message inside the class.\")\n", "\n", "myobjectx = MyClass()\n", "\n", "myobjectx.variable\n", "\n", "class MyClass:\n", " variable = \"blah\"\n", "\n", " def function(self):\n", " print(\"This is a message inside the class.\")\n", "\n", "myobjectx = MyClass()\n", "\n", "print(myobjectx.variable)\n", "\n", "class MyClass:\n", " variable = \"blah\"\n", "\n", " def function(self):\n", " print(\"This is a message inside the class.\")\n", "\n", "myobjectx = MyClass()\n", "myobjecty = MyClass()\n", "\n", "myobjecty.variable = \"yackity\"\n", "\n", "# Then print out both values\n", "print(myobjectx.variable)\n", "print(myobjecty.variable)\n", "\n", "class MyClass:\n", " variable = \"blah\"\n", "\n", " def function(self):\n", " print(\"This is a message inside the class.\")\n", "\n", "myobjectx = MyClass()\n", "\n", "myobjectx.function()\n", "\n", "class NumberHolder:\n", "\n", " def __init__(self, number):\n", " self.number = number\n", "\n", " def returnNumber(self):\n", " return self.number\n", "\n", "var = NumberHolder(7)\n", "print(var.returnNumber()) #Prints '7\n", "\n", "# define the Vehicle class\n", "class Vehicle:\n", " name = \"\"\n", " kind = \"car\"\n", " color = \"\"\n", " value = 100.00\n", " def description(self):\n", " desc_str = \"%s is a %s %s worth $%.2f.\" % (self.name, self.color, self.kind, self.value)\n", " return desc_str\n", "\n", "# your code goes here\n", "car1 = Vehicle()\n", "car1.name = \"Fer\"\n", "car1.color = \"red\"\n", "car1.kind = \"convertible\"\n", "car1.value = 60000.00\n", "\n", "car2 = Vehicle()\n", "car2.name = \"Jump\"\n", "car2.color = \"blue\"\n", "car2.kind = \"van\"\n", "car2.value = 10000.00\n", "\n", "# test code\n", "print(car1.description())\n", "print(car2.description())\n", "\n" ] }, { "cell_type": "markdown", "source": [ "# **What Is a Class in Python?**\n", "A class is a blueprint for creating objects. Classes in Python programming group related data and functions together, making code more organized, reusable, and easier to manage.\n", "\n", "Structure: Defines attributes and methods.\n", "\n", "Purpose: Helps create multiple similar objects.\n", "How to Create a Class in Python?\n", "Similar to creating a function, creating a class in Python is easy. We start by using the keyword class to indicate class creation. This is followed by the class name and a colon (:).\n", "\n", "The next indented lines will include the names of class members. The variables within a class are called attributes, which we can access later in a Python program using the dot (.) operator." ], "metadata": { "id": "a4idEYcUhN-L" } }, { "cell_type": "code", "source": [ "class Coder:\n", " language = \"Python\"\n", "\n", "# Accessing class attribute\n", "print(Coder.language)\n", "\n", "class Coder:\n", " def __init__(self, name):\n", " self.name = name\n", "\n", " def greet(self):\n", " print(\"Hello\", self.name)\n", "\n", "# Creating an object\n", "coder1 = Coder(\"Alex\")\n", "coder1.greet()\n", "\n", "class Coder:\n", " def __init__(self, name):\n", " self.name = name\n", "\n", " def greet(self):\n", " print(\"Hello\", self.name)\n", "\n", "coder1 = Coder(\"Alex\")\n", "coder1.greet()\n", "\n", "# Define a class\n", "class Car:\n", " def __init__(self, brand, model): # The __init__ method\n", " self.brand = brand # Attribute\n", " self.model = model # Attribute\n", "\n", "# Create an object (instance) of the Car class\n", "my_car = Car(\"Toyota\", \"Corolla\")\n", "\n", "# Access attributes\n", "print(my_car.brand)\n", "print(my_car.model)\n", "\n", "class Coder:\n", " def __init__(self, name, language): # Constructor to initialize attributes\n", " self.name = name\n", " self.language = language\n", "\n", " def __str__(self): # __str__ method to return a readable string\n", " return f\"{self.name} codes in {self.language}\"\n", "\n", "# Create an object of the Coder class\n", "coder1 = Coder(\"Alex\", \"Python\")\n", "\n", "# Print the object (calls __str__ method automatically)\n", "print(coder1)\n", "\n", "class Coder:\n", " # Class variable\n", " profession = \"Software Developer\"\n", "\n", " def __init__(self, name, language):\n", " # Instance variables\n", " self.name = name\n", " self.language = language\n", "\n", "# Create objects\n", "coder1 = Coder(\"Alex\", \"Python\")\n", "coder2 = Coder(\"Sara\", \"JavaScript\")\n", "\n", "# Access class and instance variables\n", "print(coder1.profession)\n", "print(coder1.name)\n", "print(coder1.language)\n", "\n", "print(coder2.profession)\n", "print(coder2.name)\n", "print(coder2.language)\n", "\n", "class Coder:\n", " def set_details(self, name, language):\n", " self.name = name # Instance variable\n", " self.language = language # Instance variable\n", "\n", "# Create object\n", "coder1 = Coder()\n", "\n", "# Set instance variables using a general method\n", "coder1.set_details(\"Alex\", \"Python\")\n", "\n", "# Access instance variables\n", "print(coder1.name)\n", "print(coder1.language)\n", "\n", "class Coder:\n", " language = \"Python\" # Class attribute\n", "\n", "# Create object\n", "coder1 = Coder()\n", "\n", "# Access class attribute using object\n", "print(coder1.language)\n", "\n", "class Coder:\n", " def __init__(self, name, language):\n", " self.name = name\n", " self.language = language\n", "\n", "# Creating multiple objects\n", "coder1 = Coder(\"Alex\", \"Python\")\n", "coder2 = Coder(\"Sara\", \"Java\")\n", "\n", "# Accessing their data\n", "print(coder1.name, \"-\", coder1.language)\n", "print(coder2.name, \"-\", coder2.language)\n", "\n", "class Coder:\n", " def __init__(self, name):\n", " self._name = name\n", "\n", " def get_name(self):\n", " return self._name\n", "\n", " def set_name(self, value):\n", " self._name = value\n", "\n", " def del_name(self):\n", " del self._name\n", "\n", " name = property(get_name, set_name, del_name)\n", "\n", "# Create object\n", "coder1 = Coder(\"Alex\")\n", "\n", "# Access and modify using property\n", "print(coder1.name)\n", "coder1.name = \"Sara\"\n", "print(coder1.name)\n", "\n", "#definition of the class starts here\n", "class Person:\n", " #initializing the variables\n", " name = \"\"\n", " age = 0\n", "\n", " #defining constructor\n", " def __init__(self, personName, personAge):\n", " self.name = personName\n", " self.age = personAge\n", "\n", " #defining class methods\n", " def showName(self):\n", " print(self.name)\n", "\n", " def showAge(self):\n", " print(self.age)\n", "\n", " #end of the class definition\n", "\n", "# Create an object of the class\n", "person1 = Person(\"John\", 23)\n", "#Create another object of the same class\n", "person2 = Person(\"Anne\", 102)\n", "#call member methods of the objects\n", "person1.showAge()\n", "person2.showName()\n", "\n", "# Create an object of the class\n", "person1 = Person(\"Richard\", 23)\n", "#Create another object of the same class\n", "person2 = Person(\"Anne\", 30)\n", "\n", "#call member methods of the objects\n", "person1.showAge()\n", "person2.showName()\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)" ], "metadata": { "id": "jjbAm-kqhOHs", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "c400b30a-56b2-46e0-9677-6045a947b2c8" }, "execution_count": 3, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Python\n", "Hello Alex\n", "Hello Alex\n", "Toyota\n", "Corolla\n", "Alex codes in Python\n", "Software Developer\n", "Alex\n", "Python\n", "Software Developer\n", "Sara\n", "JavaScript\n", "Alex\n", "Python\n", "Python\n", "Alex - Python\n", "Sara - Java\n", "Alex\n", "Sara\n", "23\n", "Anne\n", "23\n", "Anne\n", "Ozzy is 2 year(s) old.\n", "Skippy is 12 year(s) old.\n", "Filou is 8 year(s) old.\n", "2\n" ] } ] }, { "cell_type": "markdown", "source": [ "# **Python Class Attributes and Methods**\n", "For the best results, we must add some functionality to Python classes using attributes and methods. We set attributes to hold data and define functions to add behavior to the class. The functions defined within a class are called methods. The added functionalities include the following:\n", "\n", "Python Class Attributes\n", "Class attributes are variables defined inside a specific class and shared by all objects created from that class. We can access these attributes using the class name, the attribute name, and the dot (.) operator." ], "metadata": { "id": "B3P96SHyhORL" } }, { "cell_type": "code", "source": [ "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", "print(filou.buddy.name)\n", "print(filou.buddy.age)\n", "'''\n", "import pandas as pd\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", "\n", "class Person:\n", " def __init__(self, name, sex, profession):\n", " # data members (instance variables)\n", " self.name = name\n", " self.sex = sex\n", " self.profession = profession\n", "\n", " # Behavior (instance methods)\n", " def show(self):\n", " print('Name:', self.name, 'Sex:', self.sex, 'Profession:', self.profession)\n", "\n", " # Behavior (instance methods)\n", " def work(self):\n", " print(self.name, 'working as a', self.profession)\n", "\n", "# create object of a class\n", "jessa = Person('Jessa', 'Female', 'Software Engineer')\n", "\n", "# call methods\n", "jessa.show()\n", "jessa.work()\n", "\n", "class Student:\n", " # class variables\n", " school_name = 'ABC School'\n", "\n", " # constructor\n", " def __init__(self, name, age):\n", " # instance variables\n", " self.name = name\n", " self.age = age\n", "\n", "s1 = Student(\"Harry\", 12)\n", "# access instance variables\n", "print('Student:', s1.name, s1.age)\n", "\n", "# access class variable\n", "print('School name:', Student.school_name)\n", "\n", "# Modify instance variables\n", "s1.name = 'Jessa'\n", "s1.age = 14\n", "print('Student:', s1.name, s1.age)\n", "\n", "# Modify class variables\n", "Student.school_name = 'XYZ School'\n", "print('School name:', Student.school_name)\n", "\n", "# class methods demo\n", "class Student:\n", " # class variable\n", " school_name = 'ABC School'\n", "\n", " # constructor\n", " def __init__(self, name, age):\n", " # instance variables\n", " self.name = name\n", " self.age = age\n", "\n", " # instance method\n", " def show(self):\n", " # access instance variables and class variables\n", " print('Student:', self.name, self.age, Student.school_name)\n", "\n", " # instance method\n", " def change_age(self, new_age):\n", " # modify instance variable\n", " self.age = new_age\n", "\n", " # class method\n", " @classmethod\n", " def modify_school_name(cls, new_name):\n", " # modify class variable\n", " cls.school_name = new_name\n", "\n", "s1 = Student(\"Harry\", 12)\n", "\n", "# call instance methods\n", "s1.show()\n", "s1.change_age(14)\n", "\n", "# call class method\n", "Student.modify_school_name('XYZ School')\n", "# call instance methods\n", "s1.show()\n", "\n", "\n", "class Fruit:\n", " def __init__(self, name, color):\n", " self.name = name\n", " self.color = color\n", "\n", " def show(self):\n", " print(\"Fruit is\", self.name, \"and Color is\", self.color)\n", "\n", "# creating object of the class\n", "obj = Fruit(\"Apple\", \"red\")\n", "\n", "# Modifying Object Properties\n", "obj.name = \"strawberry\"\n", "\n", "# calling the instance method using the object obj\n", "obj.show()\n", "# Output Fruit is strawberry and Color is red\n", "\n", "\n", "class Fruit:\n", " def __init__(self, name, color):\n", " self.name = name\n", " self.color = color\n", "\n", " def show(self):\n", " print(\"Fruit is\", self.name, \"and Color is\", self.color)\n", "\n", "# creating object of the class\n", "obj = Fruit(\"Apple\", \"red\")\n", "\n", "# Deleting Object Properties\n", "#del obj.name\n", "\n", "# Accessing object properties after deleting\n", "print(obj.name)\n", "# Output: AttributeError: 'Fruit' object has no attribute 'name'\n", "\n", "class Employee:\n", " depatment = \"IT\"\n", "\n", " def show(self):\n", " print(\"Department is \", self.depatment)\n", "\n", "emp = Employee()\n", "emp.show()\n", "\n", "# delete object\n", "#del emp\n", "\n", "# Accessing after delete object\n", "emp.show()\n", "# Output : NameError: name 'emp' is not defined\n", "\n", "# Defining a simple class in Python\n", "class Dog:\n", " # Class attribute (shared by all Dog instances)\n", " species = \"Canis familiaris\" # scientific name for dogs\n", "\n", " # The initializer (constructor) method\n", " def __init__(self, name, age):\n", " self.name = name # Instance attribute\n", " self.age = age # Instance attribute\n", "\n", " # An instance method\n", " def description(self):\n", " return f\"{self.name} is {self.age} years old\"\n", "\n", " # Another instance method\n", " def speak(self, sound):\n", " return f\"{self.name} says {sound}\"\n", "\n", "# Creating an object (instance) of the Dog class\n", "my_dog = Dog(\"Buddy\", 5)\n", "\n", "# Accessing attributes and calling methods on the object\n", "print(my_dog.name) # Output: Buddy\n", "print(my_dog.age) # Output: 5\n", "print(my_dog.description()) # Output: Buddy is 5 years old\n", "print(my_dog.speak(\"Woof\")) # Output: Buddy says Woof\n", "\n", "\n" ], "metadata": { "id": "QpeVvysphOY0", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "c909e7fe-16e1-4c94-93e3-ca0686001444" }, "execution_count": 8, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Ozzy\n", "2\n", "Name: Jessa Sex: Female Profession: Software Engineer\n", "Jessa working as a Software Engineer\n", "Student: Harry 12\n", "School name: ABC School\n", "Student: Jessa 14\n", "School name: XYZ School\n", "Student: Harry 12 ABC School\n", "Student: Harry 14 XYZ School\n", "Fruit is strawberry and Color is red\n", "Apple\n", "Department is IT\n", "Department is IT\n", "Buddy\n", "5\n", "Buddy is 5 years old\n", "Buddy says Woof\n" ] } ] }, { "cell_type": "markdown", "source": [ "# **What Is an Object in Python?**\n", "An object in Python is a real-world instance of a class that holds actual data (attributes) and performs actions (methods) based on the class definition.\n", "\n", "Key Points:\n", "Objects are created from classes.\n", "\n", "They store data using attributes.\n", "\n", "They perform actions using methods.\n", "\n", "Each object has unique attribute values.\n", "\n", "An Object in Python Includes:\n", "State: Represents the data (attributes) of the object.\n", "\n", "Behavior: Represents the actions (methods) the object can perform.\n", "\n", "Identity: A unique name or reference for the object.\n", "Declaring Class Objects in Python\n", "In simple words, we create Python objects by calling the class name like a function. An object is just a usable version of a class that holds real values and can do actions defined in that class.\n", "\n", "Creating an Object in Python Involves:\n", "Defining a Class: We begin by writing a class that includes some variables (data) and functions (actions).\n", "\n", "Creating the Object: To make an object, we use the class name followed by brackets ().\n", "\n", "Giving Values: If needed, we can give values while creating the object to set its data.\n", "\n", "Using the Object: Once the object is ready, we can use it to get data or run its functions" ], "metadata": { "id": "uUca87tvhOlb" } } ] }