Instance methods are used for operations that involve the instance of the class. Operate on instance data.Call On object instance
Static methods are used when a method doesn't need access to the instance or the class and can be thought of as standalone functions within the class. Function-like actions associated with a class but don't need access to class or instance data. Call On class or instance (no special first argument)
###################################################################################
can we modify class data by using getter setter methods in python ?
Yes, you can modify class data using setter methods in Python, but not directly with getter methods. Here's how they work:
class Person:
@property
def name(self):
return self._name
@name.setter
def name(self, new_name):
self._name = new_name
Modifying data using a setter methods outside the class:
person = Person()
person.name = "Alice" # This calls the setter method to set the name
Getter methods:
Primarily provide a way to retrieve the value of an attribute Defined using the @property decorator.GETTER methods are (READ ONLY PROPERTY) while the SETTER methods are READ WRITE property.
While they cannot directly modify data, they can indirectly trigger changes through other methods or logic within their code.
Key points:
Setter methods are essential for controlled modification of class data, ensuring data integrity and consistency.
Getter methods, while not directly modifying data, play a crucial role in encapsulation and controlled access to class attributes.
Together, getters and setters promote a well-structured and maintainable object-oriented design.
##########################################################################
Escape Characters
>>> print('Hi this is Nagendra\'s blog')
Hi this is Nagendra's blog
Here to escape ' in Nagendra's I am using \ as a character .
\n -- New Line Charecter
\b -- BackSpace
\t -- Tab
\ -- Escape Symbol
##########################################################################
Constructer in Python
When ever if you declare Object , through that object we will call class methods ,but when we declare constructer inside a class example __init__ by default these will be invoked with out calling those by using Objects. These are called constructers in Python .
##########################################################################
# What does the Join Method do
Join method joins the elements in the List by using the separator which is used Infront of the Join. Please find the output below for reference .
# If `line` was initially a list like this:
line = ["apple", "banana", "cherry"]
# After `line = "-".join(line)`, it becomes:
line = "apple-banana-cherry"
##########################################################################
# What is a Numpy Array
The NumPy (Numeric Python) package helps us manipulate large arrays and matrices of numeric data.
To use the NumPy module, we need to import it using:
import numpy
Arrays
A NumPy array is a grid of values. They are similar to lists, except that every element of an array must be the same type.
import numpy
a = numpy.array([1,2,3,4,5])
print a[1] #2
b = numpy.array([1,2,3,4,5],float)
print b[1] #2.0
In the above example, numpy.array() is used to convert a list into a NumPy array. The second argument (float) can be used to set the type of array elements.
##########################################################################
What is 1D,2D and 3D array
1D represents single list of elements.
import numpy as np
# Create a 1D array
numbers = np.array([1, 2, 3, 4, 5])
print(numbers) # Output: [1 2 3 4 5]
2D represents a data in a matrix like structure
# Create a 2D array
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(matrix) # Output:
# [[1 2 3]
# [4 5 6]
# [7 8 9]]
3D Represent data in a cube-like structure, with multiple 2D arrays stacked together.
# Create a 3D array
cube = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
print(cube) # Output:
# [[[ 1 2 3]
# [ 4 5 6]]
# [[ 7 8 9]
# [10 11 12]]]
You can access elements using indexing:
numbers[0] : Accesses the first element of the 1D array.
matrix[1, 2] : Accesses the element at row 1, column 2 of the 2D array.
cube[0, 1, 0] : Accesses the element at the first 2D array, second row, first column of the 3D array.
################################################################################
Merging the dictionaries
Using | operator
name1 = {"kelly": 23,
"Derick": 14, "John": 7}
name2 = {"Ravi": 45, "Mpho": 67}
names = name1 | name2
print(names)
Using the merge ( ** ) operator
name1 = {"kelly": 23,
"Derick": 14, "John": 7}
name2 = {"Ravi": 45, "Mpho": 67}
names = {**name1, **name2}
print(names)
################################################################################
Counting the Item Occurrences , Writing by using the loops
list1 = ['John','Kelly', 'Peter', 'Moses', 'Peter']
# Create a count variable
count = 0
for name in list1:
if name == 'Peter':
count +=1
print(f'The name Peter appears in the list' f' {count} times.')
################################################################################
Understanding the GLOBAL variables inside the function
numbers = [1, 2, 3]
def modify_list():
numbers.append(4)
def modify_scalar():
global x
x = 10
x = 5
modify_list()
print(numbers)
modify_scalar()
print(x)
################################################################################
sys.argv -- How to use this as command line arguments
save the below code into test.py and run the code in python terminal by passing the arguments .
import sys
print ("Number of arguments:", len(sys.argv), "arguments")
print ("Argument List:", str(sys.argv))
$ python test.py arg1 arg2 arg3
Number of arguments: 4 arguments.
Argument List: ['test.py', 'arg1', 'arg2', 'arg3']
################################################################################
Writing output to the JSON file
import json
data = {
"name": "Bard",
"skills": ["coding", "writing", "humor"],
"interests": {"music": "classical", "movies": "sci-fi"}
}
with open("output.json", "w") as f:
json.dump(data, f, indent=4)
print("Data written to output.json")
#################################################################################
Reading JSON data from the String
json_string = '[{"name": "Jane", "age": 25, "interests": ["music", "books"]}, {"name": "Tom", "age": 40, "job": "doctor"}]'
import json
# Load the JSON string
data = json.loads(json_string)
# Loop through each object
for person in data:
print(f"Name: {person['name']}")
print(f"Age: {person['age']}")
# Access and print a specific value based on a key
if "interests" in person:
print(f"Interests: {person['interests']}")
elif "job" in person:
print(f"Job: {person['job']}")
print("----------")
###################################################################################
Q: Is there an easy way to tell if a variable is immutable or mutable?
A: Well…there’s the rule: numbers, strings, booleans, and tuples are immutable, whereas most everything else is mutable (such as lists, sets, and dictionaries). Things can get a little more complicated if you try to determine this at runtime. One possible technique is to pass your variable to the hash built-in. If the passed-in variable is immutable, hash returns a number. If the passed-in variable is mutable, hash fails with a TypeError, which you’d have to code for with some sort of exception-handling code. But, we might be getting ahead of ourselves here.
x = "hello"
hash(x) # Returns a hash value (strings are immutable)
y = [1, 2, 3]
hash(y) # TypeError: unhashable type: 'list' (lists are mutable)
###################################################################################
Python Exception Handling
try:
# Code that might raise an exception
except ExceptionType1:
# Code to handle ExceptionType1
except ExceptionType2:
# Code to handle ExceptionType2
...
else:
# Code to execute if no exception occurs
finally:
# Code to execute always, regardless of whether an exception occurs or not
Explanation:
try block:
Encloses the code that might raise an exception.
If no exceptions occur, execution continues normally.
except blocks:
Handle specific types of exceptions that might be raised in the try block.
You can have multiple except blocks to handle different exception types.
If an exception occurs, the corresponding except block is executed, and the rest of the try block is skipped.
else block (optional):
Executes only if no exceptions occur in the try block.
Useful for code that should run only when there are no errors.
finally block (optional):
Always executes, regardless of whether an exception occurs or not.
Often used for cleanup tasks, such as closing files or releasing resources.
Example Program
try:
num = int(input("Enter a number: "))
result = 10 / num
except ValueError:
print("Invalid input. Please enter a number.")
except ZeroDivisionError:
print("Cannot divide by zero.")
else:
print("The result is:", result)
finally:
print("This code always executes.")
Use specific exception types in except blocks for better handling.
The else block is optional and often used for code that should run only when there are no errors.
The finally block is also optional but often used for cleanup tasks, ensuring they're always executed.
This structure promotes cleaner and more error-resilient code.
###################################################################################
What is sys.exc_info() in except block of python
:
- This function returns a tuple with three items: (type, value, traceback).
##########################################################################
try:
print(100/0)
except:
print(sys.exc_info()[1] , 'Exception occured')
else:
print('No exception occurred')
finally:
print('Run this block of code always')
In Python, sys.exc_info()[1] accesses the second item of the tuple returned by the sys.exc_info() function, which represents the current exception being handled.
It's typically an instance of an exception class, such as ValueError, TypeError, ZeroDivisionError, etc.
It holds details about the error, including its message and any relevant data.
If no exception is being handled, sys.exc_info() returns a tuple of three None values.
It's generally preferred to use more specific exception handling techniques with try...except blocks, but sys.exc_info() can be useful in certain debugging or error-handling scenarios.
###################################################################################
How to handle Specific exceptions in Except block
try:
num = int(input("Enter a number: "))
result = 10 / num
except ValueError:
print("Invalid input. Please enter a number.")
except ZeroDivisionError:
print("Cannot divide by zero.")
except Exception as e: # Catch-all for any other unexpected errors
print("An unexpected error occurred:", e)
else:
print("The result is:", result)
finally:
print("This code always executes.")
###################################################################################
Python Decorators
# Apply multiple decorator on a single function
def InstallDecorator1(func):
def wrapper():
print('Please accept terms & conditions...\n')
func()
return wrapper
def InstallDecorator2(func):
def wrapper():
print('Please enter correct license key...\n')
return func()
return wrapper
def InstallDecorator3(func):
def wrapper():
print('Please enter partitioning choice...\n')
return func()
return wrapper
@InstallDecorator1
@InstallDecorator2
@InstallDecorator3
def InstallLinux():
print('Linux installation has started \n')
InstallLinux()
@ symbol: The @ symbol is used to apply decorators to the InstallLinux function.
Order of decorators: The order in which decorators are applied is crucial, as they are executed in reverse order. In this case, the order is:
@InstallDecorator3
@InstallDecorator2
@InstallDecorator1
Function Execution:
Calling InstallLinux(): When you call InstallLinux(), the following sequence occurs:
InstallDecorator3: Its wrapper function prints "Please enter partitioning choice..."
InstallDecorator2: Its wrapper function prints "Please enter correct license key..."
InstallDecorator1: Its wrapper function prints "Please accept terms & conditions..."
InstallLinux(): Finally, the original InstallLinux function executes, printing "Linux installation has started".
Output:
Please enter partitioning choice...
Please enter correct license key...
Please accept terms & conditions...
Linux installation has started
###################################################################################