text 从其他PY文件导入模块和对象
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了text 从其他PY文件导入模块和对象相关的知识,希望对你有一定的参考价值。
################################
### IMPORTING MODULES ###
################################
# Python has a 'standard' library', but you can also import libraries to use their functions.
# You can use an aliases.
import random # import the library
# you can now use the library's functions like randint by prefacing the library, such as random.randint
for i in range(5):
print(random.randint(1,10))
# You can also use a from import statement, in which case only that function will be imported. This can be
# useful if you know you're not going to need all of the functions in a library. Also, it allows you to call
# a function without having to preface it with the module name.
from random import randint
print(randint(1,10)) # you now don't need to preface it with the module like random.randint
# You can also give functions and modules aliases
import math as m
print(m.sqrt(49))
from math import sqrt as sqrt
print(s(36) # result is 36
# You can also import everything from a module at the same time using *. This makes it so you don't have to preface
# any of the functions with the module name. However, this can cause issues. If you do this for multiple modules and
# both modules have a function with the same name, if you use it later you can inadvertently call the wrong function.
# For instance, if both module1 and module2 have a sqrt function and you call it like sqrt(36), it might use the function
# from module1 when you actually want to use the function from module2. Therefore this method is usually avoided as it
# can cause ambiguity.
from random import *
print(sqrt(36))
# You can get a description of the functions contained within a module using help
help(math)
################################
### IMPORTING OBJECTS FROM OTHER PYTHON FILES ###
################################
# You can also import functions and objects from other files, as long as those files are in the same directory folder
# For Example, asy you have a file called my_python_file.py
PI = 3.14159
def myFunction(x):
return x + 2
# in another Python file, you can then import that variable and function
import my_python_file # must be in same directory
result = my_python_file.myFunction(27)
imported_number = my_python_file.PI
# You could also import in this fashion
from my_python_file import myFunction, PI
result = myFunction(PI)
# You can also change the name of variables using the 'as' keyword
import my_python_file as myFile
from my_python_file import PI as p, myFunction as mf
result = myFile.mf(p)
以上是关于text 从其他PY文件导入模块和对象的主要内容,如果未能解决你的问题,请参考以下文章