在python中实现类

时间:2010-12-06 16:07:06

标签: c++ python

嘿,这是我在cs课上做家庭作业的课程之一,现在我正在玩python。我想学习如何在python中设计类,并希望实现这一个。这是一个相对直接的课程。帮助将不胜感激。这是代码:

#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include <sstream>
#include <vector>
#include <cmath>

using namespace std;

int num_flights=0 ;
const int Columns_Total = 14; /*the total columns are 14 for each flight*/


class Flight
{
public:
Flight();
void major_calc(string& filename,ifstream& is,string& line, ofstream& os);
    void print (ofstream& os);

private:
vector<vector <double> > store;
int num_lines;
double avg_wind_speed;
double avg_height;
double avg_tempr;
double std_dev_speed;
double std_dev_height;
double std_dev_tempr;

  };

 Flight::Flight()
 {

 }

  void Flight::major_calc(string& filename,ifstream& is, string& line, ofstream& os)
   {    num_lines=0;

vector <double> single_line;  /* Vector to one test line of a flight*/
vector <double> flight_height; /* Vector stores the heights associated with all the test lines for a particular flight*/
vector <double> flight_wind_speed; /* Vector stores the wind speeds  associated with all the test lines for a particular flight*/
vector <double> flight_tempr; /*  Vector stores the temperatures  associated with all the test lines for a particular flight*/

while(getline(is,line))
{   
if (line.substr(0,3) == "ACM") /* Checks a new flight */
{
    num_flights++;
    os << line << endl;
    return ;

}
else 
{
    istringstream iss(line,istringstream::in);  /* Reading the string*/
    double FieldInfo;
    num_lines++;  /* updating the counter*/
    for (int n=0; n<14; n++)
    {
        iss >> FieldInfo;
        single_line.push_back(FieldInfo);
    }

    store.push_back(single_line);

    flight_height.push_back(single_line[4]); /* Updates the height vector with the value from a particular test line*/
    flight_wind_speed.push_back(single_line[3]); /* Updates the wind speed vector with the value from a particular test line*/
    flight_tempr.push_back(single_line[8]);/* Updates the temperature vector with the value from a particular test line*/

}

    single_line.clear(); /* Empties the single line vector so it can be used again*/

}


double temp1=0; /* temporary variables used to calculate the average height, average speed and average temperature*/
double temp2=0;
double temp3=0;

for (int i=0; i< flight_height.size();i++)
{
    temp1+= flight_height[i];
    temp2+= flight_wind_speed[i];
    temp3+= flight_tempr[i];
}

avg_height= temp1/(flight_height.size());
avg_wind_speed= temp2/(flight_wind_speed.size());
    avg_tempr= temp3/(flight_tempr.size());   


double sqr=2.0; /* Temporary variables used to calculate std deviation associate with the speed, height and the temperature*/
double temp4=0;
double temp5=0;
double temp6=0;

for (int i=0; i< flight_height.size();i++)
{
    temp4+= pow((flight_height[i]-avg_height),sqr);
            temp5+= pow((flight_wind_speed[i]-avg_wind_speed),sqr);
            temp6+= pow((flight_tempr[i]-avg_tempr),sqr);
}

std_dev_height= sqrt(temp4/flight_height.size());
std_dev_speed= sqrt(temp5/flight_wind_speed.size());
    std_dev_tempr= sqrt(temp6/flight_tempr.size());
    }

  void Flight::print (ofstream& os)
  {
os<<"printing the results out"<<endl;           /* Printing out all the values*/
os<<"avg speed: "<<avg_wind_speed<<"knots"<<endl;
os<<"avg height: "<<avg_height<<"feet"<<endl;
os<<"avg tempr: "<<avg_tempr<<"celcius"<<endl;
os<<"std dev in height: "<<std_dev_height<<"knots"<<endl;
os<<"std dev in speed: "<<std_dev_speed<<"feet"<<endl;
os<<"std dev in temperature: "<< std_dev_tempr<<"celcius"<<endl;
os<<"The number of lines "<< num_lines<<endl;

 }


   int main()
   {        
string filename;
    string line;
cout<<"Enter the filename"<<endl;
cin>>filename;
ifstream is;
    is.open(filename.c_str()); /*open the file*/
bool FileDoesntExist = is.fail();

if(FileDoesntExist) /*checks if the file exists*/
{
cout << "File doesn't exist" << endl; 
exit(1);
}

string fileout = filename.substr(filename.rfind(".")+1,filename.length()) + ".log"; /*making the ouput file */
ofstream os (fileout.c_str());

vector <Flight> complete;
while(!is.eof())
{
    Flight test;
    while(getline(is,line))
    {
        test.major_calc(filename,is,line,os);
        test.print(os);
    }
    complete.push_back(test);
}


return 0;

}

4 个答案:

答案 0 :(得分:3)

答案 1 :(得分:2)

进行转换需要了解的一些事项:

  • 在Python中,您在名为__init__()的方法(而不是Flight()或类本体本身)中对类进行初始化。
  • Python中的所有实例方法都将self作为参数
  • 要使用类引用类中的实例变量,请使用self.var
  • 在Python中,与Java,C ++等不同,对类属性的可见性几乎无法控制,因此您无法将事物声明为公共或私有(尽管您可以给它一个前导下划线,但这是一个指导原则,而不是由编译器强制执行)

修改

关于如何用Python编写C ++的其他一些注释:

  • Python中不需要std::vector之类的东西。我们只使用可以根据需要扩展和缩小的列表,可以包含任何类型的对象,可以编制索引和切片,并且可以随时使用许多方法。
  • 我确定你知道,Python是动态类型的,所以你在C ++类中做的所有类型声明 - 已成为过去

答案 2 :(得分:1)

作为一个热心的业余爱好者,我想我也会考虑到这一点。我重新安排了一些事情;我对任何可能以不同/更好的方式做出的评论表示赞赏。

import math
import os

def avg_dev(arr):
    """
    Calculate mean and standard deviation on an array of values

    @param arr Array of values
    """
    if len(arr)==0:
        return 0.0, 0.0
    else:
        avg = float(sum(arr)) / len(arr)
        dev = math.sqrt(sum([(i-avg)**2 for i in arr]))
        return avg,dev

class Flight:
    """
    Class wraps data about a single flight
    """
    def __init__(self, txt):
        """
        Initialize flight information

        @param txt  List of strings containing per-flight data
                    First row is header, beginning with 'ACM';
                    remainder are space-delimited columnar data
        """

        self.flightName = txt[0][3:].strip()
        self.numLines = len(txt)-1

        height = []
        wind = []
        temp = []
        for ln in txt[1:]:
            data = ln.split()
            height.append(float(data[4]))
            wind.append(float(data[3]))
            temp.append(float(data[8]))

        self.avg_height,     self.std_dev_height  = avg_dev(height)
        self.avg_wind_speed, self.std_dev_speed   = avg_dev(wind)
        self.avg_temp,       self.std_dev_temp    = avg_dev(temp)

    def __str__(self):
        return """Results for %s:
Speed: avg %f, stddev %f
Temp: avg %f, stddev %f
Height: avg %f, stddev %f

""" % (
            self.flightName,
            self.avg_wind_speed, self.std_dev_speed,
            self.avg_temp, self.std_dev_temp,
            self.avg_height, self.std_dev_height)


class Flights:
    """
    Container class for multiple flights expressed in a single log file
    """
    def __init__(self, fname):
        """
        Read a flight log file

        @param fname  Name of the log file
        """
        self.filename = fname
        self.flight = []

        inf = file(fname, 'r')        
        txt = []    # per-flight data buffer
        for ln in inf.readlines():
            if ln[:3]=='ACM':   # found start of new record
                if len(txt)>0:  # flush buffer
                    self.flight.append(Flight(txt))
                txt = []
            txt.append(ln)
        if len(txt)>0:          # clear buffer
            self.flight.append(Flight(txt))
        inf.close()

    def __iter__(self):
        return self.flight.__iter__()

def main():
    fname = raw_input("Enter the filename: ")

    try:
        # read flight data
        flight = Flights(fname)
    except IOError:
        print "File doesn't exist"
        sys.exit(1)

    logname = os.path.splitext(fname)[0] + ".log"
    logf = file(logname, 'w')
    for f in flight:
        logf.write(str(f))
    logf.close()

if __name__=="__main__":
    main()

对于那些想玩它的人来说,是一个伪造的测试输入文件:

ACM The first flight record
1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0 11.0 12.0 13.0 14.0
1.1 2.1 3.1 4.1 5.1 6.1 7.1 8.1 9.1 10.1 11.1 12.1 13.1 14.1
ACM The second flight
1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0 11.0 12.0 13.0 14.0
1.1 2.1 3.1 4.1 5.1 6.1 7.1 8.1 9.1 10.1 11.1 12.1 13.1 14.1
1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0 11.0 12.0 13.0 14.0
1.1 2.1 3.1 4.1 5.1 6.1 7.1 8.1 9.1 10.1 11.1 12.1 13.1 14.1
ACM Third flight
1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0 11.0 12.0 13.0 14.0
1.1 2.1 3.1 4.1 5.1 6.1 7.1 8.1 9.1 10.1 11.1 12.1 13.1 14.1
1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0 11.0 12.0 13.0 14.0

答案 3 :(得分:0)

对于main()我喜欢这个成语:

class Flight(object):
  # class defined here

if __name__ == '__main__':
  # main func defined here

然后,您可以通过在命令行上运行来单元测试/运行模块:

python flight.py