theme | class | lineNumbers | info | layout | image |
---|---|---|---|---|---|
apple-basic |
text-center |
true |
Python Basics
|
intro-image |
Python Basics - modules and class
We have learned:
- Basic data types
while
loop andfor
loopif
statement- Function definition
Ex 01 Write a function that satisfy :
func([1, 2, 3]) = 6
func([10, 2000, 1, 0]) = 2011
func([]) = 0
Try this.
def concat(*args, sep='/'):
print(args)
return sep.join(args)
print(concat('home', 'users', 'nimo'))
# ['home', 'users', 'nimo']
# 'home/users/nimo'
The argument args
captures all params to the function call.
Ex 02 Write a function that satisfy:
func(1, 2, 3) = 6
func(10, 2000, 1, 0) = 2011
func() = 0
- Assuming we have two file,
other.py
andmain.py
. - Put the function of Ex 01 and Ex 02 in
other.py
import other
print(other.func2(1, 2, 3)) # 6
Or we can use:
from other import func1, func2
print(func1([1, 2, 3, 4])) # 10
print(func2(1, 2, 3, 4)) # 10
If there are multiple functions in one module:
from other import *
print(func1()) # 0
print(func2()) # 0
- Importing a module will run the corresponding file
# other.py
var_name = 'value'
print('Hello from other.py')
# main.py
import other
- You can import variables and functions from a module
# other.py
var_name = 'value'
# main.py
from other import var_name
Each module has a name.
# other.py
# main.py
import other
print(other.__name__)
If we want some code only runs when we directly run other.py
# other.py
if __name__ == '__main__':
print('You are runing other.py')
else:
print('You are importing other.py as a module')
Try:
>>> # in python interpreter
>>> import other
# in shell
python other.py
import os.path
print(os.path.abspath('.'))
from other import func2 as my_sum
my_sum(1, 2, 3) # 6
Run the following code in python interpreter.
>>> import sys
>>> sys.ps1
>>> sys.ps1 = '??>>'
And Try this.
>>> import this