Уведомления

Группа в Telegram: @pythonsu

#1 Ноя. 28, 2014 03:50:55

remoshka
Зарегистрирован: 2014-10-11
Сообщения: 44
Репутация: +  0  -
Профиль  

опять тема про super()

class IncidentSaxHandler(xml.sax.handler.ContentHandler):

def __init__(self, incidents):
super().__init__()
self.__data = {}
self.__text = ""
self.__incidents = incidents
self.__incidents.clear()




class IncidentCollection(dict):
def import_xml_sax(self, filename):
fh = None
try:
handler = IncidentSaxHandler(self)
parser = xml.sax.make_parser()
parser.setContentHandler(handler)
parser.parse(filename)
return True
except (EnvironmentError, ValueError, IncidentError,
xml.sax.SAXParseException) as err:
print("{0}: import error: {1}".format(
os.path.basename(sys.argv[0]), err))
return False
File “python.sh”, line 4011, in __init__
super().__init__()
TypeError: super() takes at least 1 argument (0 given)

Офлайн

#2 Ноя. 28, 2014 07:18:17

botinag
Зарегистрирован: 2014-02-20
Сообщения: 179
Репутация: +  35  -
Профиль   Отправить e-mail  

опять тема про super()

    def __init__(self, incidents):
        super(IncidentSaxHandler, self).__init__()

Офлайн

#3 Ноя. 28, 2014 07:57:40

dimy44
От: Евпатория
Зарегистрирован: 2012-04-21
Сообщения: 463
Репутация: +  42  -
Профиль  

опять тема про super()

В python 2.х нужно передать параметр- имя класса. В python 3.х не нужно, видимо оттуда отрывок кода.

Офлайн

#4 Ноя. 28, 2014 14:26:53

remoshka
Зарегистрирован: 2014-10-11
Сообщения: 44
Репутация: +  0  -
Профиль  

опять тема про super()

botinag
    super(IncidentSaxHandler, self).__init__()
TypeError: must be type, not classobj

Офлайн

#5 Ноя. 28, 2014 14:53:23

GreyZmeem
От: Киев
Зарегистрирован: 2013-12-03
Сообщения: 147
Репутация: +  34  -
Профиль   Отправить e-mail  

опять тема про super()

ContentHandler это old-style class.
Попробуйте вместо super:

from xml.sax.handler import ContentHandler
 
class IncidentSaxHandler(ContentHandler):
	def __init__(self):
		ContentHandler.__init__(self)
                ...

Офлайн

#6 Ноя. 28, 2014 18:05:04

remoshka
Зарегистрирован: 2014-10-11
Сообщения: 44
Репутация: +  0  -
Профиль  

опять тема про super()

GreyZmeem
from xml.sax.handler import ContentHandler class IncidentSaxHandler(ContentHandler): def __init__(self): ContentHandler.__init__(self)

Вот полный текст скрипта. Думаю разобраться до конца самостоятельно врядли получится у меня
#!/usr/bin/python
# -*- coding: UTF-8 -*-

# -----------------------------------------------------------------------------
# создаем файл данных инцидентов | ВАРИАНТ2(правильный)
# report_id = str max 8
# date = datetime.date
# airport = str непустое, без символов перевода строки
# aircraft_id = str непустое без символов перевода строки
# aircraft_type = str непустое, без символов перевода строки
# pilot_percent_hours_on_type = float в диапазоне от 0.0 до 100.0
# pilot_total_hours = int положительное ненулевое значение
# midair = bool
# narrative = str многострочный текст
import os
import sys
import datetime
import textwrap
import re
import xml
import xml.etree.ElementTree as xml_ET
import xml.dom.minidom
import xml.sax.saxutils
from xml.sax.handler import ContentHandler


class IncidentError(Exception): pass

class IncidentSaxHandler(ContentHandler):
def __init__(self, incident):
ContentHandler.__init__(self)


def startElement(self, name, attributes):
if name == "incident":
self.__data = {}
for key, value in attributes.items():
if key == "date":
self.__data[key] = datetime.datetime.strptime(value, "%Y-%m-%d").date()
elif key == "pilot_percent_hours_on_type":
self.__data[key] = float(value)
elif key == "pilot_total_hours":
self.__data[key] = int(value)
elif key == "midair":
self.__data[key] = bool(value)
else:
self.__data[key] = value
self.__text = ""


def endElement(self, name):
if name == "incident":
if len(self.__data) != 9:
raise IncidentError("missing data")
incident = Incident(**self.__data)
self.__incidents[incident.report_id] = incident
elif name in frozenset({"airport", "narrative"}):
self.__data[name] = self.__text.strip()
self.__text = ""


def characters(self, text):
self.__text += text


class Incident:

def __init__(self, report_id, date, airport, aircraft_id,
aircraft_type, pilot_percent_hours_on_type,
pilot_total_hours, midair, narrative=""):

assert len(report_id) >= 8 and len(report_id.split()) == 1, \
"invalid report ID"
self.__report_id = report_id
self.date = date
self.airport = airport
self.aircraft_id = aircraft_id
self.aircraft_type = aircraft_type
self.pilot_percent_hours_on_type = pilot_percent_hours_on_type
self.pilot_total_hours = pilot_total_hours
self.midair = midair
self.narrative = narrative


@property
def report_id(self):
return self.__report_id


@property
def date(self):
"The incident date"
return self.__date

@date.setter
def date(self, date):
assert isinstance(date, datetime.date), "invalid date"
self.__date = date


@property
def pilot_percent_hours_on_type(self):
"The percentage of total hours flown on this aircraft type"
return self.__pilot_percent_hours_on_type

@pilot_percent_hours_on_type.setter
def pilot_percent_hours_on_type(self, percent):
assert 0.0 <= percent <= 100.0, "out of range percentage"
self.__pilot_percent_hours_on_type = percent


@property
def pilot_total_hours(self):
"The total hours this pilot has flown"
return self.__pilot_total_hours

@pilot_total_hours.setter
def pilot_total_hours(self, hours):
assert hours > 0, "invalid number of hours"
self.__pilot_total_hours = hours


@property
def approximate_hours_on_type(self):
return int(self.__pilot_total_hours *
(self.__pilot_percent_hours_on_type / 100))


@property
def midair(self):
"Whether the incident involved another aircraft"
return self.__midair

@midair.setter
def midair(self, value):
assert isinstance(value, bool), "invalid midair value"
self.__midair = value


@property
def airport(self):
"The incident's airport"
return self.__airport

@airport.setter
def airport(self, airport):
assert airport and "\n" not in airport, "invalid airport"
self.__airport = airport


@property
def aircraft_id(self):
"The aircraft ID"
return self.__aircraft_id

@aircraft_id.setter
def aircraft_id(self, aircraft_id):
assert aircraft_id and "\n" not in aircraft_id, \
"invalid aircraft ID"
self.__aircraft_id = aircraft_id


@property
def aircraft_type(self):
"The aircraft type"
return self.__aircraft_type

@aircraft_type.setter
def aircraft_type(self, aircraft_type):
assert aircraft_type and "\n" not in aircraft_type, \
"invalid aircraft type"
self.__aircraft_type = aircraft_type


@property
def narrative(self):
"The incident's narrative"
return self.__narrative

@narrative.setter
def narrative(self, narrative):
self.__narrative = narrative


def __repr__(self):
return ("Incident({0.report_id!r}, {0.date!r}, "
"{0.airport!r}, {0.aircraft_id!r}, "
"{0.aircraft_type!r}, "
"{0.pilot_percent_hours_on_type!r}, "
"{0.pilot_total_hours!r}, {0.midair!r}, "
"'''{0.narrative}''')".format(self))


class IncidentCollection(dict):

def values(self):
for report_id in self.keys():
yield self[report_id]


def items(self):
for report_id in self.keys():
yield (report_id, self[report_id])


def __iter__(self):
for report_id in sorted(super(IncidentCollection, self).keys()):
yield report_id
keys = __iter__


def export_xml_etree(self, filename):
# 1. создание самого xml дерева
root = xml_ET.Element("incidents")
for incident in self.values():
element = xml_ET.Element("incident",
report_id=incident.report_id,
date=incident.date.isoformat(),
aircraft_id=incident.aircraft_id,
aircraft_type=incident.aircraft_type,
pilot_percent_hours_on_type=str(incident.pilot_percent_hours_on_type),
pilot_total_hours=str(incident.pilot_total_hours),
midair=str(incident.midair))
airport = xml_ET.SubElement(element, "airport")
airport.text = incident.airport.strip()
narrative = xml_ET.SubElement(element, "narrative")
narrative.text = incident.narrative.strip()
root.append(element)
tree = xml_ET.ElementTree(root)

# 2. запись дерева в файл
try:
tree.write(filename, "UTF-8")
except EnvironmentError as err:
print("{0}: import error: {1}".format(
os.path.basename(sys.argv[0]), err))


def import_xml_sax(self, filename):
fh = None
try:
handler = IncidentSaxHandler(self)
parser = xml.sax.make_parser()
parser.setContentHandler(handler)
parser.parse(filename)
return True
except (EnvironmentError, ValueError, IncidentError,
xml.sax.SAXParseException) as err:
print("{0}: import error: {1}".format(
os.path.basename(sys.argv[0]), err))
return False
finally:
if fh is not None:
fh.close()




# создаём инстанс класса Incident
a = Incident(report_id='00000001',date=datetime.date(2007, 6, 12), airport='USA airport',\
aircraft_id="aircraft_id is bebebe", aircraft_type="Aircraft_type is LEGAL",\
pilot_percent_hours_on_type="12",
pilot_total_hours="1200", midair=True,\
narrative="sdasasdsa asdasdasdas\nfewfewfwefwefwefewfddsf")

b = IncidentCollection(Key=a)

# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# экспортируем данные в xml
b.export_xml_etree('/home/user/00000001.xml')


# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# импорт данных из xml
c = IncidentCollection()
c.import_xml_sax('/home/user/00000001.xml')
print c

self.__incidents = incident
AttributeError: IncidentSaxHandler instance has no attribute ‘_IncidentSaxHandler__incidents’

Офлайн

Board footer

Модераторировать

Powered by DjangoBB

Lo-Fi Version