0% found this document useful (0 votes)
5 views

sunum33

Uploaded by

esraayaksiz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

sunum33

Uploaded by

esraayaksiz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

PYTHON BASICS

-WEEK 3
Object-Oriented Programming
CLASESS
While a class is
just a template,
an object is a real
entity derived
from that
template.
OBJECTS
Object-Oriented Programming
Attributes

self.name: This is the name attribute of an object of the


Employee class.
self.age: This is the age attribute.
self.position: This is the position attribute.
self.year: This is the year attribute.

*Attributes are data or properties belonging to


objects of a class
• Methods 3.__len__(self) - Calculate the Length of the Object
Purpose: Used to return the length of the object (e.g.
1. __init__(self, ...) - Constructor Method list or string length).
Purpose: Called automatically when an object is created and Usage: Called with the len() function.
used to set the initial values of the object. class MyList:
Usage: When the object is initialized, the attributes are set with def __init__(self, items):
the __init__ method. self.items = items

class Person: def __len__(self):


def __init__(self, name, age): return len(self.items)
self.name = name
self.age = age 4.__getitem__(self, key) - Element Access
Purpose: Used to access the elements of the object by
index or key.
2. __str__(self) - Print Object
Usage: Works with the [ ] operator.
Purpose: Used to represent the object as a string in a more
understandable way.
Usage: Runs when the print() or str() function is called . class MyList:
def __getitem__(self, index):
class Person: return self.items[index]
def __str__(self):
return f"{self.name}, {self.age} years old ."
methods
5.__del__(self) - Delete Object
Purpose: Cleanup operations performed when an object is
deleted.
Usage: Called automatically when an object is deleted.

class MyClass:
def __del__(self):
print("Object deleted")

6.__eq__(self, other) - Equality Check


Purpose: Used to check equality between objects.
Usage: Called with == operator.

class Person:
def __eq__(self, other):
return self.name == other.name and self.age == other.age
Constructor (__init__)
In Python, constructor is defined as __init__() method. __init__() is the first method of the class when creating
an object and provides initialization of the object.

How Does the __init__() Method Work?


1. The first parameter of the __init__ method is always self. self refers to the currently created object. In
other words, when you run each method in the class, self specifies which object that method is running on.

2. The __init__() method is not called directly outside the class. In other words, it runs automatically when
the object is created. This method is used to set the initial data (attributes) of the object

Relationship between self and __init__


The self keyword holds the data that is valid for each object. All assignments inside the __init__ method are made
through self. In other words, the self.attribute expression expresses a value that is specific to the object.

Thanks to self, each object can have independent attributes. For example, within a Person class, each object can have a
different name and age value.
Constructor (__init__)

_init__ Method Features


-Known as a constructor, it is automatically called within the class.
-It is used to assign initial values when creating an object.
-The self parameter is required to access and initialize the object's properties.
-Flexibility can be achieved with default parameters.
__init__ is only the first method of the class and the object initialization process is
performed. It runs automatically when the object is created.
Inheritance and polymorphism
Inheritance means that a class inherits the properties and methods of another class. This way, a class can use
the functionality of another class and can be customized and extended without having to redefine it.

-The Child class inherits from the Parent class.


-The Child class inherits the Parent class's greet() method and can also use the name property.
-The super() function provides access to the methods or properties of the parent class. The
super().__init__(name) statement initializes the name property by calling the Parent class's
__init__ method.
Polymorphism
Polymorphism means that an object can behave in different ways. That is, the same method name can do
different things in different classes. Polymorphism is achieved by allowing a class's method to be
implemented in different ways or redefined in lower classes.

Advantages of Polymorphism:

.Increases the flexibility of the code: Different classes can do different


things with the same method name.

.Eases maintenance: Provides generalization of the code.


.Similar methods of different classes can have the same name.
.Eases understanding of the code: Operations can be done by focusing
on the object.
WORKING WITH LIBRARIES
o Math (mathematical functions)
The math module contains many functions that allow you to perform various mathematical operations.

import math
# Rounding operations
print("Floor (floor):", math.floor(7.8)) # Round 7.8 down
# Numerical operations print("Ceiling (ceil):", math.ceil(7.2)) # Round 7.2 up
print("Square root (sqrt ():", math.sqrt25)) # Square root of 25
print("Power (pow):", math.pow(2, 3)) # 2 to the power of 3
print("Factorial (factorial):", math.factorial(5)) # Factorial of 5 (5!)

# Trigonometric functions
angle_degrees = 60 # Constants
angle_radians = math.radians(angle_degrees) # Convert degrees to radians print("Pi:", math.pi) # Pi constant
print(f"{angle_degrees} degrees in radians:", angle_radians)
print("Sine (sin):", math.sin(angle_radians)) # Sine of 60 degrees
print("Cosine (cos):", math.cos(angle_radians)) # Cosine of 60 degrees
o Random (generating random numbers)
The random module is used to generate random numbers or make random selections.

import random

# Generate a random float between 0 and 1


print("Random float between 0 and 1:", random.random()) # A float between 0 and 1

# Generate a random integer within a range


print("Random integer between 1 and 10:", random.randint(1, 10)) # An integer between 1 and 10

# Generate a random float within a range


print("Random float between 5.5 and 10.5:", random.uniform(5.5, 10.5)) # A float between 5.5 and 10.5

# Select a random element from a list


my_list = ['apple', 'banana', 'cherry', 'date’]
print("Random choice from list:", random.choice(my_list)) # A random element from the list

# Shuffle the elements of a list


random.shuffle(my_list) # Shuffles the list in place
print("Shuffled list:", my_list)
o Datetime (date and time manipulation)
datetime module is used to work with dates and times.
import datetime
# Extracting only date and time
print("Current date:", now.date())
# Current date and time
print("Current time:", now.time())
now = datetime.datetime.now()
print("Current date and time:", now)

# Custom formatted date and time


# Today's date
formatted_date = now.strftime("%d-%m-%Y %H:%M:%S") today = datetime.date.today()
print("Formatted date and time:", formatted_date) print("Today's date:", today)

# Adding/subtracting days
future_date = now + datetime.timedelta(days=10) # Add 10 days
past_date = now - datetime.timedelta(days=10) # Subtract 10 days
print("Future date:", future_date)print("Past date:", past_date)
IMPORTING BUILT IN AND EXTERNAL MODULES

BUILT IN MODULE CREATE MODULE


There are several built-in modules in Save this code in a file named mymodule.py
Python, which you can import
whenever you like.

To see the modules available you


can use the help function:
Now we can use the module we just
created, by using the import statement:

OUTPUT
BASICS OF INSTALLING PACKAGES USING PIP.
PIP is a package manager for Python packages, or modules if you like.
Pip is a tool that is installed automatically if you've installed python 3.4 or later versions,
if you do not have PIP installed, you can download and install it.

Downloading a package is very easy.

Open the command line interface and tell


PIP to download the package you want.
COMMON PIP COMMANDS • Install a Specific Version of a Package
To install a specific version:
• Check if pip is Installed pip install <package_name>==<version>
Open your terminal or command prompt and type:
• Upgrade an Installed Package
pip --version
To upgrade an existing package:
This will display the installed pip version if it's available. pip install --upgrade <package_name>

Example:
• Upgrade pip pip install --upgrade pandas
To ensure you have the latest version:
• Uninstall a Package
pip install --upgrade pip To remove a package:
pip uninstall <package_name>
• Install a Package
• View Installed Packages
To install a package, use: To list all installed packages:
pip install <package_name> pip list

• Search for a Package


Example: To search for a package in PyPI:
pip search <keyword>
pip install matplotlib
Example:
pip search matplotlib
ACTIVITIES

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy