Friday, September 29, 2023

Python Modules Importing

 my_module.py

==========================

def greet(name):
    return f"Hello, {name} !!!"
class MyClass :
    def __init__(self,value):
        self.value = value 
    def display_value(self):
        print(f"value : {self.value}")

========================

another_script.py

===========================

import my_module
print(my_module.greet("India"))
# create MyClass obj for accessing its methods 
obj = my_module.MyClass(50)
obj.display_value()

===========================

How to import C:\Users\India\Desktop\sample.py into E:\folder\second.py  using python :

==================================================

 my_module.py

==========================

def greet(name):
    return f"Hello, {name} !!!"
class MyClass :
    def __init__(self,value):
        self.value = value 
    def display_value(self):
        print(f"value : {self.value}")

==============================

second.py 

=============================

#import sys 
import sys
# import my_module absolute path 
sys.path.append('C:/Users/India/Desktop')
# import module now 
import my_module
# use methods of my_module 
print(f"The greet() methods from my_module file : {my_module.greet("India")}")
# use MyClass methods 
obj = my_module.MyClass(50)
obj.display_value()

=============================================================

No comments:

Post a Comment

virtual environment on python on Ubuntu

 # 1. Update system and install Python tools sudo apt update && sudo apt install python3-pip python3-venv -y # 2. Setup Django in a ...