python 中的函数声明是否具有可读且干净的代码?
是否可以在 python 中声明函数并稍后定义它们或在单独的文件中定义它们?
我有一些代码,例如:
class tata:
def method1(self):
def func1():
# This local function will be only used in method1, so there is no use to
# define it outside.
# Some code for func1.
# Some code for method1.
问题是代码变得混乱且难以阅读。所以我想知道是否可以在 method1
内声明 func1
并稍后定义它?
Is it possible to declare functions in python and define them later or in a separate file?
I have some code like:
class tata:
def method1(self):
def func1():
# This local function will be only used in method1, so there is no use to
# define it outside.
# Some code for func1.
# Some code for method1.
The problem is that the code becomes messy and difficult to read. So I wonder if it's possible for instance to declare func1
inside method1
and define it later?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
当然,没问题:
foo.py:
script.py:
Sure, no problem:
foo.py:
script.py:
我认为你想要的是在
method1
中导入函数,例如Python模块基本上只是文件;只要文件
module_where_func1_is_define.py
与脚本位于同一目录中,method1
就能够导入它。如果您希望能够自定义
method1
的工作方式,并且更清楚地表明它使用func1
,您可以传递func1
将method1
作为默认参数:I think what you want is to import the function within
method1
, e.g.Python modules are basically just files; as long as the file
module_where_func1_is_defined.py
is in the same directory as your script,method1
will be able to import it.If you want to be able to customize the way
method1
works, and also make it even more clear that it usesfunc1
, you can passfunc1
tomethod1
as a default parameter:如果 func1() 需要处理 method1() 范围内包含的任何内容,那么最好将 func1() 的定义保留在那里。如果 func1() 未在 method1() 范围内定义,则必须让 func1() 接收任何相关数据作为参数
If func1() needs to handle anything contained in the scope of method1() you're best leaving func1()'s definition there. You'll have to have func1() receive any pertinent data as parameters if it's not defined within the scope of method1()
内部定义在内部作用域中创建一个单独的名称。它将隐藏您稍后定义的同名任何内容。如果您想稍后定义该函数,那就这样做吧。仅在实际使用时才会检查该名称。
The inner definition creates a separate name in the inner scope. It will shadow anything you define later on with the same name. If you want to define the function later on, then just do so. The name will only be checked for when it is actually used.
您可以随后创建方法
但是不可能有匿名函数(嗯,有 lambda 表达式,但您不能在那里有语句),因此您必须提供一个临时名称
您可能需要使用装饰器以使其更具可读性:
这段代码应该更具可读性。它仍然会污染 dummy,但将其初始化为 null。
You can create methods afterwards
However it's not possible to have an anonymous function (well, there are lambda expressions but you cannot have statements there), so you have to provide a temporary name
You might want to use decorators in order to make it more readable:
This code should be more readable. It will still pollute dummy but initialize it with null.