3

我有一个程序对数组进行一些操作(小波变换和各种其他复杂性),然后将其与前一个数组及其属性进行比较,输出一个比较两者的图形,最后更新“前一个”数组以包含此信息. 基本上,我的程序开始变得有点长且难以阅读,但我无法真正将其拆分为函数,因为所有函数都在读取并更改相同的变量。每次我想要一个函数来改变它们时,如果不将所有这些变量都定义为全局变量,那就很难了。

然后我在网上找到了这个:

您可能有多个函数使用相同的状态变量,读取或写入它们。您正在传递很多参数。您有嵌套函数,它们必须将它们的参数转发给它们使用的函数。您很想创建一些模块变量来保存状态。

您可以改为上课!一个类的所有方法都可以访问该类的所有实例数据。通过将共享状态存储在类中,您无需将其作为参数传递给方法。

所以我想知道如何使我的程序改用类来编写?如果有帮助,我可以附上我的代码,但它很长,我不想填满论坛!

这是代码:

import os, sys, string, math
from optparse import OptionParser
import numpy as np
import pywt
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
from matplotlib.ticker import MaxNLocator
import glob

dir = os.getcwd()
profiles = glob.glob(dir+"/B0740-28/*_edit.FT.ascii")
for x in range(0,len(profiles)):
    profiles[x] = profiles[x][28:]
#produce list of profile file names

mode = 'per'
wavelets = ['db12']
levels = range(3,4)
starts = []
fig = 1
ix = 0 #profile index
changes = np.zeros(len(profiles))
#array to record shape changes

for num_levels in levels:
    for wavelet in wavelets:
        for profile in profiles:

            prof_name = profile.partition('.')[0]
            #remove file extension

            pfile=open(dir+'/B0740-28/'+profile)
            data = []
            for line in pfile:
                data.append(float(line))
            data = np.array(data)
            end = len(data)
            data = np.array(data)/max(data)
            #get pulse profile and normalise
            #ignore first 2 lines

            wav_name = wavelet.partition('.')[0]
            w = pywt.Wavelet(wavelet)
            useful = pywt.dwt_max_level(end,w)
            #find max level of decomposition

            coeffs = pywt.wavedec(data,wavelet,mode,level=num_levels)
            #create wavelet coefficients: cAn, cDn, cD(n-1)... cD1

            lowpass = pywt.upcoef('a',coeffs[0],wavelet,level=num_levels,take=end)
            highpass = np.zeros(end)
            for x in range(1,(num_levels+1)):
                highpass += pywt.upcoef('d',coeffs[len(coeffs)-x],wavelet,\
                                        level=x,take=end)
            #reverse transform by upcoef
            #define highpass and lowpass components

            for n in range(0,len(data)):
                if float(data[n]) > 0.4:
                    value = n
                    starts.append(value)
                    break
            if profile != profiles[0]:
                offset = starts[0]- value
                data = np.roll(data,offset)
                lowpass = np.roll(lowpass,offset)
                highpass = np.roll(highpass,offset)
            #adjust profiles so that they line up
            
            if profile == profiles[0]:
                data_prev = 0
                lowpass_prev = 0
                highpass_prev = 0
                mxm = data.argmax()

            diff_low = lowpass - lowpass_prev
            diff_high = highpass - highpass_prev
            if max(diff_low) >= 0.15 or min(diff_low) <= -0.15:
                changes[ix] = 1
            else: changes[ix] = 0
            #significant change?

            def doPlotting(name,yaxis):
                plt.plot(name)
                plt.xlim([mxm-80,mxm+100])
                plt.ylabel(yaxis)
                plt.gca().yaxis.set_major_locator(MaxNLocator(nbins=4))
            
            figure = plt.figure(fig)
            figure.subplots_adjust(hspace =.5)
            plt.suptitle('Comparison of Consecutive Profiles')
            plt.subplot(411); plt.plot(data_prev); \
                              doPlotting(data,'Data'); plt.ylim(ymax=1.1)
            plt.subplot(412); plt.plot(lowpass_prev); \
                              doPlotting(lowpass,'Lowpass'); plt.ylim(ymax=1.1)
            plt.subplot(413); plt.plot(highpass_prev); doPlotting(highpass,'Highpass')
            plt.subplot(414); doPlotting(diff_low,'Lowpass\nChange')
            plotname = 'differences_'+str(ix+1)+'_'+wav_name+'_'+str(num_levels)
            plt.savefig(dir+'/B0740-28/Plots/'+plotname)
            #creates plots of two most recent profiles + their decomposition 

            fig += 1
            ix += 1
            #clears the figure content
            #increase array index

            data_prev = data
            lowpass_prev = lowpass
            highpass_prev = highpass
            #reassigns 'previous profile' values

figure = plt.figure(fig)
plt.plot(changes)
plt.title('Lowpass Changes')
plt.xlabel('Profile Number')
plt.ylabel('Change > Threshold?')
plt.ylim(-0.25,1.25)
plt.xlim(0,48)
plt.savefig(dir+'/B0740-28/Plots/changes')
#Save lowpass changes plot
4

2 回答 2

4

I'll probably get downvoted for this answer, but in the grand scheme of things, in this particular situation, I don't really see the problem with adding some global variables to your package.

Classes are great and useful when you have a bunch of functionality that you want to use in lots of different places, however, what you are describing sounds very specific and unlikely to be reused elsewhere. Creating a one-use class with instance variables isn't really very different to having a bunch of functions in a package with global variables.

于 2012-12-11T15:49:34.227 回答
1

Something like this is what you want:

class MyDataProcessor(object):
    def __init__(self, data_array):
        self.data_array = data_array

    def processX(self):
        # do stuff with self.data_array

    def processY(self):
        # do stuff with self.data_array

m = MyDataProcessor([1, 2, 3, 4, 5])
m.processX()

n = MyDataProcessor([5, 4, 3, 2, 1])
n.processX()
于 2012-12-11T15:48:52.530 回答