【问题标题】:How to get inheritance to work from parent to child class python34如何让继承从父类到子类python34工作
【发布时间】:2015-12-31 12:10:06
【问题描述】:

我正在尝试了解继承的概念。我正在尝试在父母(gps 类)和孩子(print_gps 类)中完成工作。我使用xlsxwriter 将gps 数据保存到excel 文件中。

由于某种原因,我无法从 gps 类中获取数据以在 print_gps 类中使用。我错过了一步吗?

import os
import csv
from csv import *
import numpy
import matplotlib
from numpy import *
from matplotlib import *
import matplotlib.pyplot as plt
from matplotlib.pylab import *
import numpy as np
#import nmea_defs
#from nmea_defs import *


#to export to excel
import xlsxwriter
from xlsxwriter.workbook import Workbook

#to get the csv converter functions
import os
import subprocess
import glob

#to get the datetime functions
import datetime
from datetime import datetime
from pytz import timezone
import time
import calendar


#creates the path needed for incoming and outgoing files
path_in = 'C:/Python34/gps_txts/'
path_out = 'C:/Python34/output_files/'

#prints all the data in the file if you want
q_show_content = input('Print list of files type y:')
if q_show_content == 'y':
    for root, dirs, files in os.walk(path_in):
          print(root, dirs, files)
else:
    print('ok')


data = []  #empty because we will store data into it



#Reads a CSV file and return it as a list of rows
def read_csv_file(filename):
    """Reads a CSV file and return it as a list of rows."""

    for row in csv.reader(open(filename)):
        data.append(row)
    return data

#request of what file to look at
print ("- - - - - - - - - - - - -")
data_file = input('Which file do you want to look at?')

f = open(path_in + data_file)
read_it = read_csv_file(path_in + data_file)

with f as csvfile:
    readCSV = csv.reader(csvfile,delimiter=',')
    plots = csv.reader(csvfile, delimiter=',')


#creates the workbook
output_filename = input('output filename:')
workbook = xlsxwriter.Workbook(path_out + output_filename + '.xlsx')
worksheet = workbook.add_worksheet()

#formatting definitions
bold    = workbook.add_format({'bold': True})
date_format = workbook.add_format({'num_format': "m/d/yyyy hh:mm:ss"})

#print number of rows
print ("- - - - - - - - - - - - -")
rows = len(read_it)
print (data_file, " has "+ str(rows) + " rows of data")
print ("- - - - - - - - - - - - -")

#Counts the number of times a GPS command is observed
def list_gps_commands(data):
    """Counts the number of times a GPS command is observed.

Returns a dictionary object."""

    gps_cmds = dict()
    for row in data:
        try:
            gps_cmds[row[0]] += 1 
        except KeyError:
            gps_cmds[row[0]] = 1

    return gps_cmds

print(list_gps_commands(read_it))
print ("- - - - - - - - - - - - -")


 #Function process_gps_data for GPS 

class gps:
    print ("- - - - - - - - - - - - -")
    print('We got class')
    print ("- - - - - - - - - - - - -")



    def process_gprmc_data(data):
        """Processes GPS data, NMEA 0183 format.
    Returns a tuple of arrays: latitude, longitude, velocity [km/h],
    time [sec] and number of satellites.
    See also: http://www.gpsinformation.org/dale/nmea.htm.
    """
        NMI = 1852.0
        latitude  = []
        longitude = []
        altitude  = []
        velocity  = []
        timestamp = []
        num_sats  = []

        print ("- - - - - - - - - - - - -")
        print('process_gprmc_data')
        print ("- - - - - - - - - - - - -")
        for row in data:

            if row[0] == '$GPRMC':     # Valid position/time sentence
                y = (float(row[3][0:2]) + float(row[3][2:])/60.0)
                if row[4] == "S":
                    y = -y
                latitude.append(y)
                x = (float(row[5][0:3]) + float(row[5][3:])/60.0)
                if row[6] == "W":
                    x = -x
                longitude.append(x)
                print('x,y:',x,y)
                velocity.append(float(row[7])*NMI/1000.0)
                gpstime = row[1][0:6]                     # hhmmss
                gdate = row[9]                            # ddmmyy
                gpsdate = gdate[4:6]+gdate[2:4]+gdate[0:2]  # yymmdd
                real_time =gpsdate + gpstime
                add_date_time = datetime.strptime(real_time, "%y%m%d%H%M%S")
                print(add_date_time)
                timestamp.append(add_date_time)
        print ("- - - - - - - - - - - - -")
        print('arrays in')
        print ("- - - - - - - - - - - - -")
        return (array(latitude), array(longitude), array(velocity), array(timestamp))

    #had to create another function to print results
class print_gps(gps):
    def __init__(self):
        self.gps = gps()        
        super(print_gps, self).__init__() 

    def process_gprmc_data(self):     
        self.gps.process_gprmc_data()
        # how to call process_gprmc_data()
        (lati, long, v, t_stamp) = self.gps.process_gprmc_data(data)
#    def print_gprmc(process_gprmc_data):
        print('got definitions in')
        print ("- - - - - - - - - - - - -")
        print('lati:',lati)
        print ("- - - - - - - - - - - - -")
        print('long:',long)
        print ("- - - - - - - - - - - - -")
        print('v:',v)
        print ("- - - - - - - - - - - - -")
        print('date:', t_stamp)
        print ("- - - - - - - - - - - - -")
        if rows > 200:
            print('Big file please wait...thinking')

        #sets up the header row
        worksheet.write('A1','TimeStamp',bold)
        worksheet.write('B1', 'Latitude',bold)
        worksheet.write('C1', 'Longitude',bold)
        worksheet.write('D1', 'Velocity',bold)
        worksheet.autofilter('A1:D1')   #dropdown menu created for filtering

        # Create a For loop to iterate through each row in the XLS file, starting at row 2 to skip the headers
        for r, row in enumerate(data, start=1):  #where you want to start printing results inside workbook
            for c, col in enumerate(data):
                worksheet.write_column(r,0, t_stamp, date_format)
                worksheet.write_column(r,1, lati)
                worksheet.write_column(r,2, long)
                worksheet.write_column(r,3, v)


        workbook.close()
        f.close()
        print('XLSX file named ' + output_filename + ' was created')


#processing piece

command = input("What type do you want to look at?")
if command == '$GPRMC':
#    nmea_defs.gps(data)
    gps.process_gprmc_data(data)
    print_gps.process_gprmc_data(data)


else:
    print("Invalid type:", command)

我得到这个结果和错误:

process_gprmc_data
- - - - - - - - - - - - -
x,y: 139.64428333333333 35.892158333333334
2001-07-18 00:24:54
x,y: 139.64430166666668 35.892201666666665
2002-07-18 00:24:56
x,y: 4.8333433333333335 45.00351833333333
2003-08-14 10:47:09
x,y: 5.00001 51.00351833333333
2004-08-14 10:47:15
- - - - - - - - - - - - -
arrays in
- - - - - - - - - - - - -
Traceback (most recent call last):
  File "C:\Python34\choose_nmea.py", line 222, in <module>
    print_gps.process_gprmc_data(data)
  File "C:\Python34\choose_nmea.py", line 171, in process_gprmc_data
    self.gps.process_gprmc_data()
AttributeError: 'list' object has no attribute 'gps'

【问题讨论】:

    标签: class python-3.x inheritance multiple-inheritance


    【解决方案1】:

    您的程序存在多个问题。

    1。缺少self

    class gpsprint_gps 更改:

    def process_gprmc_data(data):
    

    进入:

    def process_gprmc_data(self, data):
    

    2。类名使用CamleCase

    gps 重命名为GPS,将print_gps 重命名为PrintGPS

    3。无需__init__()调用

    因为GPS没有__init__(),所以PintGPS中不需要调用super()__init__()

    4。使用实例,而不是类

    变化:

    gps.process_gprmc_data(data)
    print_gps.process_gprmc_data(data)
    

    进入:

    gps = GPS()
    gps.process_gprmc_data(data)
    print_gps = PrintGPS()
    print_gps.process_gprmc_data(data)
    

    5。不要将父类的实例作为属性放在子类中

    当您使用继承时,这没有多大意义:

    self.gps = gps() 
    

    您将通过继承从父级获取方法并通过super() 调用它们(参见示例代码。)

    工作示例

    注意:由于缺少信息,我跳过了一些模式的实现。

    完整的工作代码:

    from numpy import array
    
    class GPS:
    
        def process_gprmc_data(self, data):
            """Processes GPS data, NMEA 0183 format.
        Returns a tuple of arrays: latitude, longitude, velocity [km/h],
        time [sec] and number of satellites.
        See also: http://www.gpsinformation.org/dale/nmea.htm.
        """
            NMI = 1852.0
            latitude  = []
            longitude = []
            altitude  = []
            velocity  = []
            timestamp = []
            num_sats  = []
    
            print ("- - - - - - - - - - - - -")
            print('process_gprmc_data')
            print ("- - - - - - - - - - - - -")
            for row in data:
    
                if row[0] == '$GPRMC':     # Valid position/time sentence
                    y = (float(row[3][0:2]) + float(row[3][2:])/60.0)
                    if row[4] == "S":
                        y = -y
                    latitude.append(y)
                    x = (float(row[5][0:3]) + float(row[5][3:])/60.0)
                    if row[6] == "W":
                        x = -x
                    longitude.append(x)
                    print('x,y:',x,y)
                    velocity.append(float(row[7])*NMI/1000.0)
                    gpstime = row[1][0:6]                     # hhmmss
                    gdate = row[9]                            # ddmmyy
                    gpsdate = gdate[4:6]+gdate[2:4]+gdate[0:2]  # yymmdd
                    real_time =gpsdate + gpstime
                    add_date_time = datetime.strptime(real_time, "%y%m%d%H%M%S")
                    print(add_date_time)
                    timestamp.append(add_date_time)
            print ("- - - - - - - - - - - - -")
            print('arrays in')
            print ("- - - - - - - - - - - - -")
            return (array(latitude), array(longitude), array(velocity), array(timestamp))
    
        #had to create another function to print results
    class PrintGPS(GPS):
    
        def process_gprmc_data(self, data):
            # how to call process_gprmc_data()
            (lati, long, v, t_stamp) = super(PrintGPS, self).process_gprmc_data(data)
    
            print('got definitions in')
            print ("- - - - - - - - - - - - -")
            print('lati:',lati)
            print ("- - - - - - - - - - - - -")
            print('long:',long)
            print ("- - - - - - - - - - - - -")
            print('v:',v)
            print ("- - - - - - - - - - - - -")
            print('date:', t_stamp)
            print ("- - - - - - - - - - - - -")
    
    
            output_filename = 'test.xlsx'
    
            print('XLSX file named ' + output_filename + ' was created')
    
    data = 'abc'
    gps = GPS()
    gps.process_gprmc_data(data)
    print_gps = PrintGPS()
    print_gps.process_gprmc_data(data)
    

    【讨论】:

    • 我更改了它,但现在我收到错误 Traceback(最近一次调用最后一次):文件“C:\Python34\choose_nmea.py”,第 214 行,在 gps.process_gprmc_data( data) TypeError: process_gprmc_data() missing 1 required positional argument: 'data'.. 为什么我必须为那个添加一个 self 参数?
    • 我是 python 新手,通过我正在进行的示例和项目来学习。如果您能帮我弄清楚如何在这个项目中使用继承方法,我将不胜感激。我尝试阅读所有在线教程,但我似乎无法弄清楚如何使用它。
    • 谢谢迈克!我添加了完整的代码,这样你就可以看到我一直在做什么。
    • 哇..谢谢迈克!!!!有用!!!!一旦我完全分析了你给我的代码,我可能还有一些额外的问题。如果这样可以吗?
    • 一般建议:尝试将您的大问题划分为小的、理想情况下独立的子问题。只是问一个新问题。通常,最好制作一个仍然显示您的案例的玩具示例。
    猜你喜欢
    • 2019-12-28
    • 1970-01-01
    • 1970-01-01
    • 2019-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多