Python: Unterschied zwischen den Versionen
Zur Navigation springen
Zur Suche springen
Zeile 74: | Zeile 74: | ||
date1 = datetime.datetime(2019, 4, 1, 22, 44, 12, 123456) | date1 = datetime.datetime(2019, 4, 1, 22, 44, 12, 123456) | ||
now = datetime.datetime.now() | now = datetime.datetime.now() | ||
daylySeconds = (now.time().hour*60+now.time().minute)*60+now.time().second | |||
yesterday = datetime.datetime.fromtimestamp(time.time() - 24*3600) | yesterday = datetime.datetime.fromtimestamp(time.time() - 24*3600) | ||
firstOfMonth = date1.replace(day=1) | firstOfMonth = date1.replace(day=1) |
Version vom 11. April 2019, 22:27 Uhr
Exception
try: raise Exception("not allowed") except ValueError as error: print('value error: ' + repr(error)) except SyntaxError as error: print('syntax error: ' + repr(error)) else: raise Exception("unknown") try: doit() finally: closeIt()
Regular Expression
rexpr = compile(r"([\da-z]+)") match = rexpr.match(line) if match != None: number = (int) rexpr.group(1)
Datentypen
String
- "x" und 'x' sind gleichwertig
- Formatierung
"{:3.7f} {:s} {:07d}".format(3.14, "hello", 100) "{0:d} / {0:x}".format(714) "{}-{}: {}".format('abc.txt', 9, 7.99)
Container
- List: ['a', 1]; x[1] = 5; x.insert(0, 'firstItem'); x.remove('a'); ix=x.index('a'); del x[0];
- Tupel: t = ('a', 1); l = list(t)
Dictionary
x = { 'key' : 'val', 'xyz': 3 } x['key'] = value del x['key']; contains = 'key' in x and 'key2' not in x size = len(x) for pair in x.iteritems(): key = pair[0] for key in x.iterkeys(): print key
- x.itervalues()
- x.setdefault(key[, value]): setzt Wert nur, wenn noch nicht gesetzt
- x.keys(), x.values()
- x.copy(): flache Kopie
- x.update(dict): addiert dict zu x
Mengen
s = set(['y', 3]) ; f = frozenset(['y', 3]) for elem in s: print elem size = len(s) contains = 3 in s and 4 not in s intersection = s & f union = s | f isPartOf = s <= f diff = s - f
Datum/Zeit
import datetime, time # ab hour optional: date1 = datetime.datetime(2019, 4, 1, 22, 44, 12, 123456) now = datetime.datetime.now() daylySeconds = (now.time().hour*60+now.time().minute)*60+now.time().second yesterday = datetime.datetime.fromtimestamp(time.time() - 24*3600) firstOfMonth = date1.replace(day=1) asStringMicroseconds = date1.strftime('%Y.%m.%dT%H:%M:%S.%f dayOfTheWeek: %w')
Typcheck
isStringOrSubclass = isinstance(aVariable, str) isString = type(aVariable) is str isList = type([1, 2]) is list isDict = type({ 0:"a", 1:"b" }) is dict
Spezielle Methoden/Attribute
- Statische Methoden:
class X: # statische Variable _data = [] @staticmethod def add(item): X._data.append(item) X.add("new")
- Feststellen, ob Attribut existiert: hasattr(instance, nameOfAttribute)
- dynamischer Code:
exec 'import ' + module
- Vollständige Kopie (deep copy):
import copy x = [1, 2] y = copy.deepcopy(x)
- Superclass-Konstruktor:
class Parent: def __init__(self, name) self._name = name class Child(Parent): def __init__(self, name): Parser.__init__(self, name)
Typische Situationen
Externes Programm aufrufen
with supbprocess.popen([ '/usr/bin/wc', '-l', file ], stdout=subprocess.PIPE) as proc: count = int(proc.stdout.read().decode())
Dateien
- Lesen:
with open(self._filename, "r") as fp: for line in fp: print(line) # fp.close() ist implizit
- Schreiben:
with open(self._filename, "w") as fp: fp.write("Hello\nWorld\n");
Sprachbesonderheiten
Verschachtelte Methoden
class Example: def scan(self, file): lineNo = 0 for line in file: lineNo += 1 if line.startswith('[': chapter = Chapter(line[1:-1]) elif re.match(r'\w+='): var, value = line.split('=') chapter._vars[var] = value else: _error('invalid input') def _error(msg): print("line {}: {}\n{}".format(lineNo, msg, line)
Klasse als Sequenz
Damit eine Klasse mit "x in classInstance" angesprochen werden kann, muss es einen Iterator geben. Im Beispiel wird dies in einer Klasse zusammengefasst:__iter__() liefert als Iterator sich selbst und __next__() implementiert diesen Iterator:
class Example: def __init__(): self._nextItems = [] def __iter__(): self._nextItems = [1, 2, 3] return self def __next__(): if len(self._nextItem) == 0: raise StopIteration else: rc = self._nextItems[0] del self._nextItems[0] return rc def next(): return self.__next__()