Function declaration in python to have a readable and clean code?
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?
Sure, no problem:
foo.py:
def func1():
pass
script.py:
import foo
class tata:
def method1(self):
func1=foo.func1
I think what you want is to import the function within method1
, e.g.
def method1(...):
from module_where_func1_is_defined import func1
# do stuff
something = func1(stuff, more_stuff)
# do more stuff
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 uses func1
, you can pass func1
to method1
as a default parameter:
import other_module
# various codes
def method1(other_args, func=other_module.func1)
# do stuff
something = func(stuff, more_stuff)
# do more stuff
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.
def foo():
print 'foo'
bar()
def bar():
print 'bar'
foo()
You can create methods afterwards
class Something(object): def test1(self): pass def dummy(self): print "ok", self Something.test1 = dummy
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:
def define(cls, name): def decor(f): setattr(cls, name, f) return decor class Something(object): def test1(self): pass @define(Something, "test1") def dummy(self): print "ok", self
This code should be more readable. It will still pollute dummy but initialize it with null.
精彩评论