【发布时间】:2018-08-18 01:14:37
【问题描述】:
我有很多类,里面的功能都差不多。
说函数x:
class A():
def x_A (self):
...
...do the same thing
...
run a function that is unique in class A itself, say u_A
...
...do the same thing
...
class B():
def x_B (self):
...
...do the same thing
..
run a function that is unique in class B itself, say u_B
...
...do the same thing
...
所以我想出了一个想法,在一个新类中重写函数 x(比如 C 类中的 x_C)来替换 x_A 和 x_B。我只需要在需要时导入那个新类。类似:
import C
class A():
def x_A (self):
C.x_C(u_A)
class B():
def x_B (self):
C.x_C(u_A)
但我对如何将唯一函数(u_A 和 u_B)作为变量传递并让 python 正常运行感到困惑。
class C():
def x_C (self,unique_function):
...
...do the same thing
..
run unique_function here
...
...do the same thing
...
提前谢谢
blow 是新编辑的:
您好,想说明我的问题:
我有许多爬虫,在每个爬虫的末尾我都有“run_before_insert”来检查它们是否可以正常运行。 目前我只是在每个完成的爬虫的末尾复制并粘贴这个函数并进行一些编辑。 但是现在我想通过从其他文件中导入“run_before_insert”来简化我的代码,然后我的问题就来了。
def run_before_insert(self):
try:
#store_list = []
comp_name = 'HangTen'
start = time.time()
print('{} runBeforeInsert START'.format(comp_name), '\n')
###Here is the part where small edits in the function:
store_list = self.get_stores_2()
###the rest is the same
script_info = {}
running_time = round(time.time() - start,2)
total = str(len(store_list))
script_info['running_time'] = running_time
script_info['total_stores'] = total
print('\n{} total stores : {}'.format(comp_name,script_info['total_stores']), '\n')
print('{} running time : {}'.format(comp_name,script_info['running_time']), '\n')
print('{} runBeforeInsert Done'.format(comp_name), '\n')
print('\n')
return script_info
except Exception as e:
traceback.print_exc()
script_info = {}
script_info['running_time'] = '--'
script_info['total_stores'] = 'error'
return script_info
print(e)
这是我参考@juanpa.arrivillaga 的代码:
class run_pkg_class():
def __init__(self):
pass
def run_before_insert(self, store_function, company_name):
try:
comp_name = company_name
start = time.time()
print('{} runBeforeInsert START'.format(comp_name), '\n')
###
store_list = store_function()
###
script_info = {}
running_time = round(time.time() - start,2)
total = str(len(store_list))
script_info['running_time'] = running_time
script_info['total_stores'] = total
print('\n{} total stores : {}'.format(comp_name,script_info['total_stores']), '\n')
print('{} running time : {}'.format(comp_name,script_info['running_time']), '\n')
print('{} runBeforeInsert Done'.format(comp_name), '\n')
print('\n')
return script_info
except Exception as e:
traceback.print_exc()
script_info = {}
script_info['running_time'] = '--'
script_info['total_stores'] = 'error'
return script_info
print(e)
并在上面导入hangten爬虫类:
def run_before_insert2(self):
rp = run_pkg_class()
rp.run_before_insert(self.get_id())
在这个 hangTen 的情况下,self.get_stores_2() 将返回一个列表。
“TypeError: 'list' object is not callable”在运行时发生。
不确定原因
【问题讨论】:
-
import C不会导入类,它会导入一个模块(通常是由源文件C.py定义的模块)。另外,如果C是一个类而不是一个模块,而x_C是那个类中的普通方法,你不能调用C.x_C,你必须构造一个实例,@ 987654332@,然后您可以拨打c.x_C。 -
同时,使用具体、有意义的名称而不是
C和x_C之类的名称可能会更容易解释。
标签: python python-3.x function class