I've created several functions
#generate .h file template for class
def generateHeaderClassTemplate(name):
template = open('header.template', 'r')
code = parseHeaderTemplate(template.read(), name)
template.close()
return code
#generate .cpp file template for class
def generateImplClassTemplate(name):
template = open('class.template', 'r')
code = parseImplTemplate(template.read(), name)
template.close()
return code
#generate main.cpp file template
def generateMainTemplate():
template = open('main.template', 'r')
code = parseMainTemplate(template.read())
template.close()
return code
But the problem is that they are all basically the same
1. open file
2. write there some function result
3. close file
4. return data
So I want to create some universal function which will have function as parameter, filename as parameter and parameter for the function. And then function like generateHeaderClassTemplate
will be something like
def generateHeaderClassTemplate(name):
return generateTemplate(parseHeaderTemplate, 'header.template', name)
Basically I want function like this
def generateTemplate(func, templateFile, name):
template = open(templateFile, 'r')
code = func(template.read(), name) #or code = func(template.read()) if name was not passed
template.close()
return code
But how to make it work as in comment I wrote - If I do not pass name
- perform func(template.read())
and if I pass it - perform func(template.read(), name)
?
Using python optional arguments
http://www.diveintopython.net/power_of_introspection/optional_arguments.html
When you declare the function you can pass default values to arguments, so if you don't pass them into the function when you call it by default it will use those parameters, like this example:
def info(object, spacing=10, collapse=1):
spacing defaults to 10 and collapse to 1
You can use default value for the parameters:
def generateTemplate(func, templateFile, name=None):
this way you can use generateTemplate
with or without a third argument:
generateTemplate(parseImplTemplate, 'f')
generateTemplate(parseMainTemplate, 'f', 'foo)
And in the generateTemplate
definition, you can do something like:
def generateTemplate(func, templateFile, name=None):
template = open(templateFile, 'r')
if name:
code = func(template.read(), name)
else:
code = func(template.read())
template.close()
return code
Perhaps a default value to the parameter name would help you
def test(a, b = ""):
print (a, b)
test ("hello")
test ("hello", "world")
Your template methids must always have the same prototype, generateTemplateFun(name="")
but when calling them you can skip the name part making the code cleaner
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.