简体   繁体   English

如何将功能从.py文件导入到另一个.py文件?

[英]How to import functions from a .py file to another .py file?

I learned to use java functions before python functions, and generally I make a different classes for different "public static voids" so my main code regroup all of my functions. 我学会了在python函数之前使用java函数,并且通常我为不同的“ public static voids”创建不同的类,因此我的主要代码重新组合了所有函数。 And when I wanted to do the same and I tried: 当我想做同样的事情时,我尝试了:

global def function():
print("String")

and

def global function():
print("String")

and some alternative ways (eg Make my function in another class, com back in my main and put "global function") but I still can't make global functions... So if anyone has the answer, just tell me! 以及其他一些替代方法(例如,将函数创建到另一个类中,再次输入main并放入“全局函数”),但是我仍然无法创建全局函数...因此,如果有人有答案,请告诉我!

In general you should build your Python projects as modules using __init__.py and setuptools . 通常,您应该使用__init__.pysetuptools将Python项目构建为模块。 I usually just have a utilities type of module in my projects that contains all of my "global" functions. 我的项目中通常只有一个utilities类型的模块,其中包含所有“全局”功能。 I then import that module wherever I need it and invoke the functions. 然后,在需要的地方导入该模块并调用函数。

The functions can be defined normally with this approach, eg def my_function(): 可以使用这种方法正常定义函数,例如def my_function():

The standard in python is that any function which begins with an underline character is considered private while everything else would be considered public and accessible by anything/anyone. python中的标准是,任何以下划线字符开头的函数均被视为private函数,而其他所有函数均被视为公共函数,任何人/任何人都可以访问。

Python is not Java. Python不是Java。 You can declare functions outside of any class declaration, and you can then import them in the current namespace in you want to. 您可以在任何类声明之外声明函数,然后可以将它们导入所需的当前名称空间中。

Example: a file containing some functions (lets us call it glob_funcs.py) 示例:包含一些功能的文件(让我们将其称为glob_funcs.py)

def foo():
    return "Foo"

def bar(x):
    return "Bar >{}<".format(x)

How to import them: 如何导入它们:

from glob_funcs import foo, bar
print(foo())       # prints Foo
print(bar(foo())   # prints Bar >Foo<

When you create a class in python, its variables and methods are public by default. 在python中创建类时,默认情况下其变量和方法是公共的。 If you want to make your data protected you prefix the name with an underscore. 如果要保护数据,请在名称前加上下划线。 If you want to make it private you prefix it with at least two underscores. 如果要将其设为私有,请在其前面至少添加两个下划线。 For example: 例如:

class Something:
    def __init__(self):
        self.name = None # public variable
        self._grade = None # protected variable
        self.__pass = None # private variable

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM