从现有python代码创建方法
我有一段python脚本的代码,我必须查询用户的ldap属性:从现有python代码创建方法,python,function,methods,Python,Function,Methods,我有一段python脚本的代码,我必须查询用户的ldap属性: try: ldap_result_id = l.search(baseDN, searchScope, get_searchFilter(adname), retrieveAttributes) result_set = [] while 1: result_type, result_data = l.result(ldap_result_id, 0) if (result_
try:
ldap_result_id = l.search(baseDN, searchScope, get_searchFilter(adname),
retrieveAttributes)
result_set = []
while 1:
result_type, result_data = l.result(ldap_result_id, 0)
if (result_data == []):
break
else:
## you could do whatever you want with the individual entry
## The appending to list is just for illustration.
if result_type == ldap.RES_SEARCH_ENTRY:
result_set.append(result_data)
for x in result_set:
print x
except ldap.LDAPError, e:
print e
print ldap.LDAPError
如何将其清理并使其成为一个可重用的函数或方法是更合适的术语?确定可以更改的变量,并将这些参数添加到函数中。将打印和异常处理放在函数之外,除非您可以对异常执行合理的操作:
def fn(baseDN, searchScope, adname, retrieveAttributes):
ldap_result_id = l.search(baseDN, searchScope, get_searchFilter(adname),
retrieveAttributes)
result_set = []
while 1:
result_type, result_data = l.result(ldap_result_id, 0)
if (result_data == []):
break
else:
## you could do whatever you want with the individual entry
## The appending to list is just for illustration.
if result_type == ldap.RES_SEARCH_ENTRY:
result_set.append(result_data)
return result_set
baseDN = ???
searchScope = ???
adname = ???
retrieveAttributes = ???
try:
for x in fn(baseDN, searchScope, adname, retrieveAttributes):
print x
except ldap.LDAPError, e:
print e
print ldap.LDAPError
因为您不打算生成类,所以函数是更合适的术语,也是唯一正确的术语。@DYZ如果我开始使用类,那么它会是一个方法吗?只有当它是类的一部分时才是。我假设baseDN=?,searchScope=?,adname=???检索属性=???脚本中是否应该省略?这些是需要提供的变量,例如用户输入、从数据存储读取、由另一个应用程序传递等。明白了!是的,我已经在另一部分的python脚本中提供了这些!你的解决方案非常有效!