Scopes & NameSpaces
Object: In general, anything that can be assigned to a variable in Python is referred to as an object. Strings, Integers, Floats, Lists, Functions, Module etc. are all objects.
Namespaces: A namespace is a collection of currently defined names along with information about the object that the name references. It ensures that names are unique and won’t lead to any conflict.
Types of namespaces:
Built-in Namespace: Created when we start executing a Python program and exists as long as the program is running. This is the reason that built-in functions like id()
, print()
etc. are always available to us from any part of the program.
Global Namespace: This namespace includes all names defined directly in a module (outside of all functions). It is created when the module is loaded, and it lasts until the program ends.
Local Namespace: Modules can have various functions and classes. A new local namespace is created when a function is called, which lasts until the function returns.
Scope of a Name:
In Python, the scope of a name refers to where it can be used. The name is searched for in the local, global, and built-in namespaces in that order.
Global variables: In Python, a variable defined outside of all functions is known as a global variable. This variable name will be part of Global Namespace.
Local Variables: In Python, a variable defined inside a function is a local variable. This variable name will be part of the Local Namespace.
Local Variables & Global Variables:
Modifying Global Variables: global
keyword is used to define a name to refer to the value in Global Namespace.
Python Standard Library
The collection of predefined utilities is referred as the Python Standard Library. All these functionalities are organized into different modules.
Module: In Python context, any file containing Python code is called a module.
Package: These modules are further organized into folders known as packages.
Importing module: To use a functionality defined in a module we need to import that module in our program.
Importing from a Module: We can import just a specific definition from a module.
Aliasing Imports: We can also import a specific definition from a module and alias it.
Random module: Randomness is useful in whenever uncertainty is required.
Example: Rolling a dice, flipping a coin, etc,.
random
module provides us utilities to create randomness.
Randint: randint()
is a function in random module which returns a random integer in the given interval.
Choice: choice()
is a function in random module which returns a random element from the sequence.
Classes
Classes: Classes can be used to bundle related attributes and methods. To create a class, use the keyword class
Self: self
passed to method contains the object, which is an instance of class.
Special Method: In Python, a special method __init__
is used to assign values to attributes.
Instance of Class: Syntax for creating an instance of class looks similar to function call. An instance of class is an Object.
Class Object: An object is simply a collection of attributes and methods that act on those data.
Attributes of an Object: Attributes can be set or accessed using .
(dot) character.
Accessing in Other Methods: We can also access and update attributes in other methods.
Updating Attributes: It is recommended to update attributes through methods.
Instance Attributes: Attributes whose value can differ for each instance of class are modelled as instance attributes.
Accessing Instance Attributes: Instance attributes can only be accessed using instance of class.
Class Attributes: Attributes whose values stay common for all the objects are modelled as Class Attributes.
Accessing Class Attributes:
Updating Class Attribute:
Methods: Broadly, methods can be categorized as
- Instance Methods
- Class Methods
- Static Methods
Instance Methods: Instance methods can access all attributes of the instance and have self
as a parameter.
Class Methods: Methods which need access to class attributes but not instance attributes are marked as Class Methods. For class methods, we send cls
as a parameter indicating we are passing the class.
Static Method: Usually, static methods are used to create utility functions which make more sense to be part of the class. @staticmethod
decorator marks the method below it as a static method.
Instance Methods | Class Methods | Methods |
---|---|---|
self as parameter | cls as parameter | No cls or self as parameters |
No decorator required | Need decorator @classmethod | Need decorator @staticmethod |
Can be accessed through object(instance of class) | Can be accessed through class | Can be accessed through class |
OOPS
OOPS: Object-Oriented Programming System (OOPS) is a way of approaching, designing, developing software that is easy to change.
Bundling Data: While modeling real-life objects with object oriented programming, we ensure to bundle related information together to clearly separate information of different objects.
Encapsulation: Bundling of related properties and actions together is called Encapsulation. Classes can be used to bundle related attributes and methods.
Inheritance: Inheritance is a mechanism by which a class inherits attributes and methods from another class. Prefer modeling with inheritance when the classes have an IS-A
relationship.
Super Class & Sub Class:
- Superclass cannot access the methods and attributes of the subclass.
- The subclass automatically inherits all the attributes & methods from its superclass.
Calling Super Class Method: We can call methods defined in the superclass from the methods in the subclass.
Composition: Modeling instances of one class as attributes of another class is called Composition. Prefer modeling with inheritance when the classes have an HAS-A
relationship.
Overriding Methods: Sometimes, we require a method in the instances of a sub class to behave differently from the method in instance of a superclass.
Accessing Super Class’s Method: super()
allows us to call methods of the superclass (Product) from the subclass. Instead of writing and methods to access and modify warranty we can override __init__
.
MultiLevel Inheritance: We can also inherit from a subclass. This is called MultiLevel Inheritance.
Inheritance & Composition:
Inheritance | Composition | |
---|---|---|
Car is a vehicle | Car has a Tyre | |
Truck is a vehicle | Order has a product |
Errors & Exceptions
Errors & Exceptions: There are two major kinds of errors:
- Syntax Errors
- Exceptions
Syntax Errors: Syntax errors are parsing errors which occur when the code is not adhering to Python Syntax.
- When there is a syntax error, the program will not execute even if that part of code is not used.
Exceptions: Errors detected during execution are called exceptions.
Division Example: Input given by the user is not within expected values.
Working With Exceptions:
Raising Exceptions:
Handling Exceptions: Exceptions can be handled with try-except
block. Whenever an exception occurs at some line in try block, the execution stops at that line and jumps to except block.
Handling Specific Exceptions: We can specifically mention the name of exception to catch all exceptions of that specific type.
Handling Multiple Exceptions: We can write multiple exception blocks to handle different types of exceptions differently.
Working With Dates & Times
Datetime: Python has a built-in datetime
module which provides convenient objects to work with dates and times.
Datetime classes: Commonly used classes in the datetime module are:
1
. date class
2
. time class
3
. datetime class
4
. timedelta class
Representing Date: A date object can be used to represent any valid date (year, month and day).
Attributes of Date Object:
Today’s Date: Class method today()
returns a date object with today’s date.
Representing Time: A time object can be used to represent any valid time (hours, minutes and seconds).
Attributes of Time Object:
Datetime: The datetime
class represents a valid date and time together.
Timedelta: Timedelta object represents duration.
Calculating Time Difference:
Formatting Datetime: The datetime classes have strftime(format)
method to format the datetime into any required format like
- mm/dd/yyyy
- dd-mm-yyyy
Parsing Datetime: The class method strptime()
creates a datetime
object from a given string representing date and time.