在python中使用其他类的函数

时间:2018-08-18 01:14:37

标签: python python-3.x function class

我有很多类,其中的函数几乎相同。

说功能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
        ...

提前谢谢

打击是新编辑的:

您好想指定我的问题:

我有多个搜寻器,每个搜寻器的末尾都有“ 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())

在这种情况下,self.get_stores_2()将返回一个列表。

在运行时发生“ TypeError:'列表'对象不可调用”。

不确定原因

2 个答案:

答案 0 :(得分:0)

Python函数是一流的对象。它们就像其他任何属性一样。只需直接通过它们即可:

import C

class A:
    def x_A (self):
        C.x_C(self.u_A)

class B:
    def x_B (self):
        C.x_C(self.u_B)

C中,您可以这样称呼它:

unique_function()

考虑到C显然并不关心AB中的状态,我怀疑这些东西不应该从类开始。

答案 1 :(得分:0)

如果我理解正确,您甚至不需要每次都导入模块。相反,您可以创建一个基本类,其他类将从该基本类继承该函数。例如,类B和C从类A继承函数“ power”。

class A:
    """ Example of class A """
    def __init__(self):
        self.num1 = num1

    def power(self, num):
        return num**3

class B (A):
    """ Example of class B"""

    def __init__(self, num1, num2):
        super().__init__(num1)
        self.num2 = num2
        self.power_num1 = self.power(num1)

class C(A):
    """ Example of class C"""

    def __init__(self, num1, num2, num3):
        super().__init__(num1)
        self.num2 = num2
        self.num3 = num3

    def power_total(self):
        print(self.power(self.num1) + self.power(self.num2)
              + self.power(self.num3))

使用示例:

>>> c = C(1, 2, 3)
>>> c.power_total()
36
>>> b = B(2, 4)
>>> b.power_num1
8