python_classes_filesetc
python_classes_filesetc
-----------------------
Python is an object oriented programming language.
Create a Class
---------------
To create a class, use the keyword class:
class MyClass:
x = 5
Create Object
--------------
Now we can use the class named MyClass to create objects:
Example
Create an object named p1, and print the value of x:
p1 = MyClass()
print(p1.x)
All classes have a function called __init__(), which is always executed when the
class is being initiated.
Example
--------
Create a class named Person, use the __init__() function to assign values for name
and age:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
Note: The __init__() function is called automatically every time the class is being
used to create a new object.
The __str__() Function
-----------------------
The __str__() function controls what should be returned when the class object is
represented as a string.
If the __str__() function is not set, the string representation of the object is
returned:
Example
--------
The string representation of an object WITHOUT the __str__() function:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1)
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name}({self.age})"
p1 = Person("John", 36)
print(p1)
Object Methods
---------------
Objects can also contain methods. Methods in objects are functions that belong to
the object.
Example
-------
Insert a function that prints a greeting, and execute it on the p1 object:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
It does not have to be named self , you can call it whatever you like, but it has
to be the first parameter of any function in the class:
Example
--------
Use the words mysillyobject and abc instead of self:
class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.myfunc()
Example
-------
Set the age of p1 to 40:
p1.age = 40
Example
--------
Delete the age property from the p1 object:
del p1.age
Delete Objects
--------------
You can delete objects by using the del keyword:
Example
-------
Delete the p1 object:
del p1
Example
-------
class Person:
pass
Python Inheritance
-------------------
Inheritance allows us to define a class that inherits all the methods and
properties from another class.
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived
class.
Create a class named Person, with firstname and lastname properties, and a
printname method:
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
#Use the Person class to create an object, and then execute the printname method:
x = Person("John", "Doe")
x.printname()
Example
Create a class named Student, which will inherit the properties and methods from
the Person class:
class Student(Person):
pass
Note: Use the pass keyword when you do not want to add any other properties or
methods to the class.
Now the Student class has the same properties and methods as the Person class.
Example
--------
Use the Student class to create an object, and then execute the printname method:
x = Student("Mike", "Olsen")
x.printname()
We want to add the __init__() function to the child class (instead of the pass
keyword).
Note: The __init__() function is called automatically every time the class is being
used to create a new object.
Example
Add the __init__() function to the Student class:
class Student(Person):
def __init__(self, fname, lname):
#add properties etc.
When you add the __init__() function, the child class will no longer inherit the
parent's __init__() function.
Note: The child's __init__() function overrides the inheritance of the parent's
__init__() function.
To keep the inheritance of the parent's __init__() function, add a call to the
parent's __init__() function:
Example
-------
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
Now we have successfully added the __init__() function, and kept the inheritance of
the parent class, and we are ready to add functionality in the __init__() function.
Example
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
Add Properties
---------------
Example
Add a property called graduationyear to the Student class:
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
self.graduationyear = 2019
In the example below, the year 2019 should be a variable, and passed into the
Student class when creating student objects. To do so, add another parameter in the
__init__() function:
Example
-------
Add a year parameter, and pass the correct year when creating objects:
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
Add Methods
-------------
Example
-------
Add a method called welcome to the Student class:
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
def welcome(self):
print("Welcome", self.firstname, self.lastname, "to the class of",
self.graduationyear)
Python Iterators
----------------
An iterator is an object that contains a countable number of values.
An iterator is an object that can be iterated upon, meaning that you can traverse
through all the values.
Lists, tuples, dictionaries, and sets are all iterable objects. They are iterable
containers which you can get an iterator from.
All these objects have a iter() method which is used to get an iterator:
Example
-------
Return an iterator from a tuple, and print each value:
print(next(myit))
print(next(myit))
print(next(myit))
Example
-------
Strings are also iterable objects, containing a sequence of characters:
mystr = "banana"
myit = iter(mystr)
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
Example
-------
Iterate the values of a tuple:
for x in mytuple:
print(x)
Example
--------
Iterate the characters of a string:
mystr = "banana"
for x in mystr:
print(x)
Example
--------
Create an iterator that returns numbers, starting with 1, and each sequence will
increase by one (returning 1,2,3,4,5 etc.):
class MyNumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
x = self.a
self.a += 1
return x
myclass = MyNumbers()
myiter = iter(myclass)
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
Python Polymorphism
--------------------
The word "polymorphism" means "many forms", and in programming it refers to
methods/functions/operators with the same name that can be executed on many objects
or classes.
Function Polymorphism
---------------------
An example of a Python function that can be used on different objects is the len()
function.
String
------
For strings len() returns the number of characters:
Example
-------
x = "Hello World!"
print(len(x))
Tuple
-----
For tuples len() returns the number of items in the tuple:
Example
-------
mytuple = ("apple", "banana", "cherry")
print(len(mytuple))
Dictionary
----------
For dictionaries len() returns the number of key/value pairs in the dictionary:
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(len(thisdict))
Class Polymorphism
-------------------
Polymorphism is often used in Class methods, where we can have multiple classes
with the same method name.
For example, say we have three classes: Car, Boat, and Plane, and they all have a
method called move():
Example
-------
Different classes with the same method:
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def move(self):
print("Drive!")
class Boat:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def move(self):
print("Sail!")
class Plane:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def move(self):
print("Fly!")
Yes. If we use the example above and make a parent class called Vehicle, and make
Car, Boat, Plane child classes of Vehicle, the child classes inherits the Vehicle
methods, but can override them:
Example
-------
Create a class called Vehicle and make Car, Boat, Plane child classes of Vehicle:
class Vehicle:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def move(self):
print("Move!")
class Car(Vehicle):
pass
class Boat(Vehicle):
def move(self):
print("Sail!")
class Plane(Vehicle):
def move(self):
print("Fly!")
Child classes inherits the properties and methods from the parent class.
In the example above you can see that the Car class is empty, but it inherits
brand, model, and move() from Vehicle.
The Boat and Plane classes also inherit brand, model, and move() from Vehicle, but
they both override the move() method.
Because of polymorphism we can execute the same method for all classes.
Python Scope
-------------
A variable is only available from inside the region it is created. This is called
scope.
Local Scope
-----------
A variable created inside a function belongs to the local scope of that function,
and can only be used inside that function.
Example
--------
A variable created inside a function is available inside that function:
def myfunc():
x = 300
print(x)
myfunc()
Example
-------
The local variable can be accessed from a function within the function:
def myfunc():
x = 300
def myinnerfunc():
print(x)
myinnerfunc()
myfunc()
Global Scope
-------------
A variable created in the main body of the Python code is a global variable and
belongs to the global scope.
Global variables are available from within any scope, global and local.
Example
--------
A variable created outside of a function is global and can be used by anyone:
x = 300
def myfunc():
print(x)
myfunc()
print(x)
Naming Variables
-----------------
If you operate with the same variable name inside and outside of a function, Python
will treat them as two separate variables, one available in the global scope
(outside the function) and one available in the local scope (inside the function):
Example
-------
The function will print the local x, and then the code will print the global x:
x = 300
def myfunc():
x = 200
print(x)
myfunc()
print(x)
Global Keyword
--------------
If you need to create a global variable, but are stuck in the local scope, you can
use the global keyword.
Example
--------
If you use the global keyword, the variable belongs to the global scope:
def myfunc():
global x
x = 300
myfunc()
print(x)
Also, use the global keyword if you want to make a change to a global variable
inside a function.
Example
-------
To change the value of a global variable inside a function, refer to the variable
by using the global keyword:
x = 300
def myfunc():
global x
x = 200
myfunc()
print(x)
Nonlocal Keyword
----------------
The nonlocal keyword is used to work with variables inside nested functions.
The nonlocal keyword makes the variable belong to the outer function.
Example
-------
If you use the nonlocal keyword, the variable will belong to the outer function:
def myfunc1():
x = "Jane"
def myfunc2():
nonlocal x
x = "hello"
myfunc2()
return x
print(myfunc1())
Python Modules
---------------
What is a Module?
Consider a module to be the same as a code library.
Create a Module
----------------
To create a module just save the code you want in a file with the file
extension .py:
Example
-------
Save this code in a file named mymodule.py
def greeting(name):
print("Hello, " + name)
Use a Module
------------
Now we can use the module we just created, by using the import statement:
Example
Import the module named mymodule, and call the greeting function:
import mymodule
mymodule.greeting("Ranganadh")
Variables in Module
-------------------
The module can contain functions, as already described, but also variables of all
types (arrays, dictionaries, objects etc):
Example
-------
Save this code in the file mymodule.py
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Example
--------
Import the module named mymodule, and access the person1 dictionary:
import mymodule
a = mymodule.person1["age"]
print(a)
Naming a Module
---------------
You can name the module file whatever you like, but it must have the file extension
.py
Re-naming a Module
-------------------
You can create an alias when you import a module, by using the as keyword:
Example
--------
Create an alias for mymodule called mx:
import mymodule as mx
a = mx.person1["age"]
print(a)
Built-in Modules
----------------
There are several built-in modules in Python, which you can import whenever you
like.
Example
-------
Import and use the platform module:
import platform
x = platform.system()
print(x)
Example
--------
List all the defined names belonging to the platform module:
import platform
x = dir(platform)
print(x)
Note: The dir() function can be used on all modules, also the ones you create
yourself.
Example
--------
The module named mymodule has one function and one dictionary:
def greeting(name):
print("Hello, " + name)
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Example
--------
Import only the person1 dictionary from the module:
print (person1["age"])
Note: When importing using the from keyword, do not use the module name when
referring to elements in the module. Example: person1["age"], not
mymodule.person1["age"]
Python Datetime
---------------
Python Dates
------------
A date in Python is not a data type of its own, but we can import a module named
datetime to work with dates as date objects.
Example
-------
Import the datetime module and display the current date:
import datetime
x = datetime.datetime.now()
print(x)
Date Output
-----------
When we execute the code from the example above the result will be:
2024-04-29 11:38:08.036860
The date contains year, month, day, hour, minute, second, and microsecond.
The datetime module has many methods to return information about the date object.
Example
-------
Return the year and name of weekday:
import datetime
x = datetime.datetime.now()
print(x.year)
print(x.strftime("%A"))
The datetime() class requires three parameters to create a date: year, month, day.
Example
-------
Create a date object:
import datetime
x = datetime.datetime(2020, 5, 17)
print(x)
The datetime() class also takes parameters for time and timezone (hour, minute,
second, microsecond, tzone), but they are optional, and has a default value of 0,
(None for timezone).
The method is called strftime(), and takes one parameter, format, to specify the
format of the returned string:
Example
=======
Display the name of the month:
import datetime
x = datetime.datetime(2018, 6, 1)
print(x.strftime("%B"))
A reference of all the legal format codes:
Python Math
------------
Python has a set of built-in math functions, including an extensive math module,
that allows you to perform mathematical tasks on numbers.
Example
-------
x = min(5, 10, 25)
y = max(5, 10, 25)
print(x)
print(y)
The abs() function returns the absolute (positive) value of the specified number:
Example
--------
x = abs(-7.25)
print(x)
Example
-------
Return the value of 4 to the power of 3 (same as 4 * 4 * 4):
x = pow(4, 3)
print(x)
import math
When you have imported the math module, you can start using methods and constants
of the module.
The math.sqrt() method for example, returns the square root of a number:
Example
import math
x = math.sqrt(64)
print(x)
The math.ceil() method rounds a number upwards to its nearest integer, and the
math.floor() method rounds a number downwards to its nearest integer, and returns
the result:
Example
--------
import math
x = math.ceil(1.4)
y = math.floor(1.4)
print(x) # returns 2
print(y) # returns 1
Example
-------
import math
x = math.pi
print(x)
Math Methods
--------------
Method Description
math.ceil() Rounds a number up to the nearest integer
math.comb() Returns the number of ways to choose k items from n items
without repetition and order
math.exp() Returns E raised to the power of x
math.fabs() Returns the absolute value of a number
math.factorial() Returns the factorial of a number
math.floor() Rounds a number down to the nearest integer
math.fmod() Returns the remainder of x/y
math.gcd() Returns the greatest common divisor of two integers
math.isnan() Checks whether a value is NaN (not a number) or not
math.isqrt() Rounds a square root number downwards to the nearest integer
math.log() Returns the natural logarithm of a number, or the logarithm of number
to base
math.log10() Returns the base-10 logarithm of x
math.pow() Returns the value of x to the power of y
math.remainder() Returns the closest value that can make numerator
completely divisible by the denominator
math.sqrt() Returns the square root of a number
math.trunc() Returns the truncated integer parts of a number
Math Constants
---------------
Constant Description
math.e Returns Euler's number (2.7182...)
math.pi Returns PI (3.1415...)
math.tau Returns tau (6.2831...)
Statistics Methods
-------------------
Method Description
statistics.mean() Calculates the mean (average) of the given data
Example
--------
Calculate the average of the given data:
Example
Calculate the median (middle value) of the given data:
Example
Calculate the variance from a sample of data:
Method Description
close() Closes the file
readline() Returns one line from the file
readlines() Returns a list of lines from the file
seek() Change the file position
tell() Returns the current file position
truncate() Resizes the file to a specified size
write() Writes the specified string to the file
writelines() Writes a list of strings to the file
Exception Description
ArithmeticError Raised when an error occurs in numeric calculations
Exception Base class for all exceptions
EOFError Raised when the input() method hits an "end of file" condition
(EOF)
IndentationError Raised when indentation is not correct
IndexError Raised when an index of a sequence does not existValueErrorRaised
when there is a wrong value in a specified data type
ZeroDivisionError Raised when the second operator in a division is zero
Python Try Except
--------------------
The try block lets you test a block of code for errors.
The else block lets you execute code when there is no error.
The finally block lets you execute code, regardless of the result of the try- and
except blocks.
Exception Handling
--------------------
When an error occurs, or exception as we call it, Python will normally stop and
generate an error message.
Example
-------
The try block will generate an exception, because x is not defined:
try:
print(x)
except:
print("An exception occurred")
Since the try block raises an error, the except block will be executed.
Without the try block, the program will crash and raise an error:
Example
-------
This statement will raise an error, because x is not defined:
print(x)
Many Exceptions
---------------
You can define as many exception blocks as you want, e.g. if you want to execute a
special block of code for a special kind of error:
Example
Print one message if the try block raises a NameError and another for other errors:
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
Else
You can use the else keyword to define a block of code to be executed if no errors
were raised:
Example
--------
In this example, the try block does not generate any error:
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
Finally
The finally block, if specified, will be executed regardless if the try block
raises an error or not.
Example
--------
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
This can be useful to close objects and clean up resources:
Example
--------
Try to open and write to a file that is not writable:
try:
f = open("demofile.txt")
try:
f.write("Lorum Ipsum")
except:
print("Something went wrong when writing to the file")
finally:
f.close()
except:
print("Something went wrong when opening the file")
The program can continue, without leaving the file object open.
Raise an exception
------------------
As a Python developer you can choose to throw an exception if a condition occurs.
Example
-------
Raise an error and stop the program if x is lower than 0:
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
You can define what kind of error to raise, and the text to print to the user.
Example
-------
Raise a TypeError if x is not an integer:
x = "hello"
Python PIP
-----------
What is PIP?
PIP is a package manager for Python packages, or modules if you like.
Note: If you have Python version 3.4 or later, PIP is included by default.
What is a Package?
A package contains all the files you need for a module.
Modules are Python code libraries you can include in your project.
Example
-------
Check PIP version:
Using a Package
--------------
Once the package is installed, it is ready to use.
Example
Import and use "camelcase":
import camelcase
c = camelcase.CamelCase()
print(c.hump(txt))
Remove a Package
-----------------
Use the uninstall command to remove a package:
Example
Uninstall the package named "camelcase":
List Packages
--------------
Use the list command to list all the packages installed on your system:
Example
List installed packages:
File Handling
The key function for working with files in Python is the open() function.
"r" - Read - Default value. Opens a file for reading, error if the file does not
exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists
In addition you can specify if the file should be handled as binary or text mode
Syntax
To open a file for reading it is enough to specify the name of the file:
f = open("demofile.txt")
The code above is the same as:
f = open("demofile.txt", "rt")
Because "r" for read, and "t" for text are the default values, you do not need to
specify them.
Note: Make sure the file exists, or else you will get an error.
demofile.txt
The open() function returns a file object, which has a read() method for reading
the content of the file:
If the file is located in a different location, you will have to specify the file
path, like this:
Example
Open a file on a different location:
f = open("D:\\myfiles\welcome.txt", "r")
print(f.read())
Example
Return the 5 first characters of the file:
f = open("demofile.txt", "r")
print(f.read(5))
Read Lines
You can return one line by using the readline() method:
Example
Read one line of the file:
f = open("demofile.txt", "r")
print(f.readline())
By calling readline() two times, you can read the two first lines:
Example
Read two lines of the file:
f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())
By looping through the lines of the file, you can read the whole file, line by
line:
Example
Loop through the file line by line:
f = open("demofile.txt", "r")
for x in f:
print(x)
Close Files
It is a good practice to always close the file when you are done with it.
Example
Close the file when you are finish with it:
f = open("demofile.txt", "r")
print(f.readline())
f.close()
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
Example
Open the file "demofile3.txt" and overwrite the content:
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()
"x" - Create - will create a file, returns an error if the file exist
"a" - Append - will create a file if the specified file does not exist
"w" - Write - will create a file if the specified file does not exist
Example
Create a file called "myfile.txt":
f = open("myfile.txt", "x")
Result: a new empty file is created!
Example
Create a new file if it does not exist:
f = open("myfile.txt", "w")
Delete a File
To delete a file, you must import the OS module, and run its os.remove() function:
import os
os.remove("demofile.txt")
Check if File exist:
To avoid getting an error, you might want to check if the file exists before you
try to delete it:
Example
Check if file exists, then delete it:
import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")
Delete Folder
To delete an entire folder, use the os.rmdir() method:
Example
Remove the folder "myfolder":
import os
os.rmdir("myfolder")
Note: You can only remove empty folders.