【问题标题】:use functions from other class in python在python中使用其他类的函数
【发布时间】: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
  • 同时,使用具体、有意义的名称而不是 Cx_C 之类的名称可能会更容易解释。

标签: python python-3.x function class


【解决方案1】:

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 中的状态,我怀疑这些东西不应该从类开始。

【讨论】:

  • 我想创建一个类C的原因是将来可能在A类和B类中运行其他类似的功能。或者也许还有其他更好的做法?
  • 您可以拥有不在类中且不绑定到对象的函数。
  • @Pete 是的,模块级函数在这里似乎非常合适。如果没有更具体的细节,很难给出更具体的建议。
【解决方案2】:

如果我理解正确,您甚至不需要每次都导入模块。相反,您可以创建一个基本类,其他类将从中继承该函数。例如,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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    • 2013-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多