Python:在另一个文件/类中将某些实例方法的定义分开

时间:2018-07-12 09:55:29

标签: python

我有一堂课

class Foo:
    def __init__(self, df):
        self.df = df
        self.keys = []

    def startJob(self):
        self.first_job()
        self.second_job()
        self.third_job()

    def first_job(self):
        #do soemthing with df

    def second_job(self):
        #do soemthing with df

    def third_job(self):
        #do soemthing with df

乔布斯列表可能很小,因此我想将乔布斯分成第二个文件,仅将__init__startJob放在第一个文件中。我该怎么做,还有没有更好的方法来实现这种分离以提高可读性?

2 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

# jobs.py

__all__ = ["jobs"]

jobs = []

def register(job):
    jobs.append(job)
    return job

## WARNING: the definition order is important

@register
def first_job(self):
    # ...

@register
def second_job(self): 
   # ...

然后:

# foo.py

from jobs import jobs

class Foo:
    def __init__(self, df, jobs=jobs):
        self.jobs = jobs
        self.df = df
        self.keys = []

    def start_job(self):
        for job in self.jobs:
            job(self)

答案 1 :(得分:0)

具有依赖注入概念的可能实现之一:

import pandas as pd

class Foo:
    def __init__(self, df):
        self.df = df
        self.keys = []
        self.runner = FooJobRunner(self)  # initiate specialized job processor

    def startJob(self):
        self.runner.first_job()
        self.runner.second_job()
        self.runner.third_job()


class FooJobRunner:
    ''' Class which serves as a job processor specifically for Foo instances '''

    def __init__(self, foo):
        if not isinstance(foo, Foo):
            raise TypeError('Foo instance required!')
        self.foo = foo

    def first_job(self):
        print(self.foo.df['a'])
        print('1st job ended\n')

    def second_job(self):
        print(self.foo.df['b'])
        print('2nd job ended\n')

    def third_job(self):
        print(self.foo.df['c'])
        print('3rd job ended\n')

# sample dataframe        
df = pd.DataFrame({'a': [1,2,3], 'b': [4,5,6], 'c': [7,8,9]})
foo = Foo(df)
foo.startJob()

输出:

0    1
1    2
2    3
Name: a, dtype: int64
1st job ended

0    4
1    5
2    6
Name: b, dtype: int64
2nd job ended

0    7
1    8
2    9
Name: c, dtype: int64
3rd job ended