如何让 Python .py 文件共享变量和常量?
How Can I Make Python .py Files Share Variables & Constants?
我在大学里一直在学习 C++,我感兴趣的一件事是创建共享头文件的能力,以便所有 cpp 文件都可以访问其中的对象。我想知道是否有某种方法可以在 python 中使用变量和常量做同样的事情?我只知道如何导入和使用其他py文件中的函数或类。
如果您只是想定义函数,那么这个 post 可能会回答您的问题:
Python: How to import other Python files
然后你可以按照这里定义一个函数:
https://www.tutorialspoint.com/python/python_functions.htm
或者,如果您想制作 class:
https://docs.python.org/3/tutorial/classes.html
您可以查看前面link中的示例3.9.5,以了解如何在不同的对象实例之间创建共享变量。
首先,如果您曾经使用过sys.argv
或os.sep
,那么您已经使用过其他模块的变量和常量。
因为共享变量和常量的方式与共享函数的方式完全相同,类。
事实上,函数、类、变量、常量——就Python而言,它们都只是模块全局变量。它们可能具有不同类型的值,但它们是同一类变量。
那么,假设您编写了这个模块:
# spam.py
cheese = ['Gouda', 'Edam']
def breakfast():
print(cheese[-1])
如果你import spam
,你可以使用cheese
,与使用eggs
完全一样:
import spam
# call a function
spam.eggs()
# access a variable
print(spam.cheese)
# mutate a variable's value
spam.cheese.append('Leyden')
spam.eggs() # now it prints Leyden instead of Edam
# even rebind a variable
spam.cheese = (1, 2, 3, 4)
spam.eggs() # now it prints 4
# even rebind a function
spam.eggs = lambda: print('monkeypatched')
spam.eggs()
C++ 头文件实际上只是一个穷人的模块。并非每种语言都像 Python 一样灵活,但是从 Ruby 到 Rust 的几乎每种语言都有某种真正的模块系统;只有 C++(和 C)要求您通过在编译时将代码包含到一堆不同的文件中来伪造它。
我在大学里一直在学习 C++,我感兴趣的一件事是创建共享头文件的能力,以便所有 cpp 文件都可以访问其中的对象。我想知道是否有某种方法可以在 python 中使用变量和常量做同样的事情?我只知道如何导入和使用其他py文件中的函数或类。
如果您只是想定义函数,那么这个 post 可能会回答您的问题:
Python: How to import other Python files
然后你可以按照这里定义一个函数:
https://www.tutorialspoint.com/python/python_functions.htm
或者,如果您想制作 class:
https://docs.python.org/3/tutorial/classes.html
您可以查看前面link中的示例3.9.5,以了解如何在不同的对象实例之间创建共享变量。
首先,如果您曾经使用过sys.argv
或os.sep
,那么您已经使用过其他模块的变量和常量。
因为共享变量和常量的方式与共享函数的方式完全相同,类。
事实上,函数、类、变量、常量——就Python而言,它们都只是模块全局变量。它们可能具有不同类型的值,但它们是同一类变量。
那么,假设您编写了这个模块:
# spam.py
cheese = ['Gouda', 'Edam']
def breakfast():
print(cheese[-1])
如果你import spam
,你可以使用cheese
,与使用eggs
完全一样:
import spam
# call a function
spam.eggs()
# access a variable
print(spam.cheese)
# mutate a variable's value
spam.cheese.append('Leyden')
spam.eggs() # now it prints Leyden instead of Edam
# even rebind a variable
spam.cheese = (1, 2, 3, 4)
spam.eggs() # now it prints 4
# even rebind a function
spam.eggs = lambda: print('monkeypatched')
spam.eggs()
C++ 头文件实际上只是一个穷人的模块。并非每种语言都像 Python 一样灵活,但是从 Ruby 到 Rust 的几乎每种语言都有某种真正的模块系统;只有 C++(和 C)要求您通过在编译时将代码包含到一堆不同的文件中来伪造它。