Bearbeiten von „Python“
Zur Navigation springen
Zur Suche springen
Warnung: Du bist nicht angemeldet. Deine IP-Adresse wird bei Bearbeitungen öffentlich sichtbar. Melde dich an oder erstelle ein Benutzerkonto, damit Bearbeitungen deinem Benutzernamen zugeordnet werden.
Die Bearbeitung kann rückgängig gemacht werden. Bitte prüfe den Vergleich unten, um sicherzustellen, dass du dies tun möchtest, und veröffentliche dann unten deine Änderungen, um die Bearbeitung rückgängig zu machen.
Aktuelle Version | Dein Text | ||
Zeile 1: | Zeile 1: | ||
[[Kategorie:Sprache]] | [[Kategorie:Sprache]] | ||
= Exception = | = Exception = | ||
< | <pre> | ||
try: | try: | ||
raise Exception("not allowed") | raise Exception("not allowed") | ||
Zeile 18: | Zeile 14: | ||
finally: | finally: | ||
closeIt() | closeIt() | ||
</ | </pre> | ||
= Regular Expression = | = Regular Expression = | ||
< | <pre> | ||
rexpr = compile(r"([\da-z]+)") | |||
rexpr = | |||
match = rexpr.match(line) | match = rexpr.match(line) | ||
if match != None: | if match != None: | ||
number = (int) rexpr.group(1) | number = (int) rexpr.group(1) | ||
</pre> | |||
</ | |||
= Datentypen = | = Datentypen = | ||
== String == | == String == | ||
* "x" und 'x' sind gleichwertig | * "x" und 'x' sind gleichwertig | ||
* Formatierung | |||
<pre> | |||
< | |||
"{:3.7f} {:s} {:07d}".format(3.14, "hello", 100) | "{:3.7f} {:s} {:07d}".format(3.14, "hello", 100) | ||
"{0:d} / {0:x}".format(714) | "{0:d} / {0:x}".format(714) | ||
"{}-{}: {}".format('abc.txt', 9, 7.99) | "{}-{}: {}".format('abc.txt', 9, 7.99) | ||
</pre> | |||
</ | |||
* Bytes -> String: b'data'.decode("utf-8") | * Bytes -> String: b'data'.decode("utf-8") | ||
* String -> Bytes: "string".encode("utf-8") | * String -> Bytes: "string".encode("utf-8") | ||
== Container (List) == | == Container (List) == | ||
* List: ['a', 1]; x[1] = 5; x.insert(0, 'firstItem'); x.remove('a'); ix=x.index('a'); del x[0]; | * List: ['a', 1]; x[1] = 5; x.insert(0, 'firstItem'); x.remove('a'); ix=x.index('a'); del x[0]; | ||
** list1 = list1 + list2 | ** list1 = list1 + list2 | ||
* Tupel: t = ('a', 1); l = list(t) | * Tupel: t = ('a', 1); l = list(t) | ||
* list2 = [x for x in range(3)] | * list2 = [x for x in range(3)] | ||
== Dictionary== | == Dictionary== | ||
< | <pre> | ||
x = { 'key' : 'val', 'xyz': 3 } | x = { 'key' : 'val', 'xyz': 3 } | ||
x['key'] = value | x['key'] = value | ||
Zeile 87: | Zeile 49: | ||
contains = 'key' in x and 'key2' not in x | contains = 'key' in x and 'key2' not in x | ||
size = len(x) | size = len(x) | ||
for | for pair in x.iteritems(): | ||
key = pair[0] | |||
for key in x: | for key in x.iterkeys(): | ||
print key | print key | ||
</ | </pre> | ||
* x.itervalues() | * x.itervalues() | ||
* x.setdefault(key[, value]): setzt Wert nur, wenn noch nicht gesetzt | * x.setdefault(key[, value]): setzt Wert nur, wenn noch nicht gesetzt | ||
Zeile 99: | Zeile 61: | ||
== Mengen == | == Mengen == | ||
< | <pre> | ||
s = | s = set(['y', 3]) ; f = frozenset(['y', 3]) | ||
f = frozenset( | |||
for elem in s: | for elem in s: | ||
print elem | print elem | ||
Zeile 116: | Zeile 71: | ||
isPartOf = s <= f | isPartOf = s <= f | ||
diff = s - f | diff = s - f | ||
</ | </pre> | ||
== Datum/Zeit == | == Datum/Zeit == | ||
< | <pre>import datetime, time | ||
import datetime, time | |||
# ab hour optional: | # ab hour optional: | ||
date1 = datetime.datetime(2019, 4, 1, 22, 44, 12, 123456) | date1 = datetime.datetime(2019, 4, 1, 22, 44, 12, 123456) | ||
formatted = date1.strftime('%Y.%m.%dT%H:%M:%S') | formatted = date1.strftime('%Y.%m.%dT%H:%M:%S') | ||
now = datetime.datetime.now() | now = datetime.datetime.now() | ||
Zeile 135: | Zeile 88: | ||
date3 = time.localtime(date2) | date3 = time.localtime(date2) | ||
date4 = time.strftime('%Y.%m.%d-%H:%M:%S.%f dayOfTheWeek: %w', date3) | date4 = time.strftime('%Y.%m.%d-%H:%M:%S.%f dayOfTheWeek: %w', date3) | ||
# Scannen aus Text: | # Scannen aus Text: | ||
date5 = datetime.datetime | date5 = datetime.datetime("30 Nov 00", "%d %b %y") | ||
timeTuple = time.strptime("30 Nov 00", "%d %b %y") | timeTuple = time.strptime("30 Nov 00", "%d %b %y") | ||
# mktime interpretiert lokale Zeit! | # mktime interpretiert lokale Zeit! | ||
Zeile 143: | Zeile 95: | ||
# calendar.timegm()¶ interpretiert GM-Time | # calendar.timegm()¶ interpretiert GM-Time | ||
time3 = calendar.timegm(timeTuple) | time3 = calendar.timegm(timeTuple) | ||
</pre> | |||
</ | |||
== Typcheck == | == Typcheck == | ||
< | <pre> | ||
isStringOrSubclass = isinstance(aVariable, str) | isStringOrSubclass = isinstance(aVariable, str) | ||
isString = type(aVariable) is str | isString = type(aVariable) is str | ||
isList = type([1, 2]) is list | isList = type([1, 2]) is list | ||
isDict = type({ 0:"a", 1:"b" }) is dict | isDict = type({ 0:"a", 1:"b" }) is dict | ||
</ | </pre> | ||
== Spezielle Methoden/Attribute == | == Spezielle Methoden/Attribute == | ||
* Statische Methoden: | * Statische Methoden: | ||
< | <pre> | ||
class X: | class X: | ||
# statische Variable | # statische Variable | ||
Zeile 193: | Zeile 116: | ||
X.add("new") | X.add("new") | ||
</ | </pre> | ||
* Feststellen, ob Attribut existiert: hasattr(instance, nameOfAttribute) | * Feststellen, ob Attribut existiert: hasattr(instance, nameOfAttribute) | ||
* dynamischer Code: | * dynamischer Code: | ||
< | <pre> | ||
exec 'import ' + module | exec 'import ' + module | ||
</ | </pre> | ||
* Vollständige Kopie (deep copy): | * Vollständige Kopie (deep copy): | ||
< | <pre> | ||
import copy | import copy | ||
x = [1, 2] | x = [1, 2] | ||
y = copy.deepcopy(x) | y = copy.deepcopy(x) | ||
</ | </pre> | ||
* Superclass-Konstruktor: | * Superclass-Konstruktor: | ||
< | <pre> | ||
class Parent: | class Parent: | ||
def __init__(self, name) | def __init__(self, name) | ||
Zeile 213: | Zeile 136: | ||
def __init__(self, name): | def __init__(self, name): | ||
Parser.__init__(self, name) | Parser.__init__(self, name) | ||
</ | </pre> | ||
== Funktionale Programmierung == | == Funktionale Programmierung == | ||
< | <pre> | ||
import functools, math | import functools, math | ||
array = [ 1, 9, 7, 5 ] | array = [ 1, 9, 7, 5 ] | ||
Zeile 222: | Zeile 145: | ||
squares = list(map(lambda x: x*x, array)) | squares = list(map(lambda x: x*x, array)) | ||
squares2 = list(filter(lambda x: int(math.sqrt(x)) == math.sqrt(x), array)) | squares2 = list(filter(lambda x: int(math.sqrt(x)) == math.sqrt(x), array)) | ||
</ | </pre> | ||
= Typische Situationen = | = Typische Situationen = | ||
== Externes Programm aufrufen == | == Externes Programm aufrufen == | ||
< | <pre> | ||
with supbprocess.popen([ '/usr/bin/wc', '-l', file ], stdout=subprocess.PIPE) as proc: | with supbprocess.popen([ '/usr/bin/wc', '-l', file ], stdout=subprocess.PIPE) as proc: | ||
count = int(proc.stdout.read().decode()) | count = int(proc.stdout.read().decode()) | ||
</ | </pre> | ||
== Dateien == | == Dateien == | ||
* Lesen: | * Lesen: | ||
< | <pre> | ||
with open(self._filename, "r") as fp: | with open(self._filename, "r") as fp: | ||
for line in fp: | for line in fp: | ||
print(line) | print(line) | ||
# fp.close() ist implizit | # fp.close() ist implizit | ||
</ | </pre> | ||
* Schreiben: | * Schreiben: | ||
< | <pre> | ||
with open(self._filename, "w") as fp | with open(self._filename, "w") as fp: | ||
fp.write("Hello\nWorld\n"); | |||
fp.write( | </pre> | ||
</ | |||
= Sprachbesonderheiten = | = Sprachbesonderheiten = | ||
== Aufruf Superclass-Konstruktor == | == Aufruf Superclass-Konstruktor == | ||
< | <pre>class B (A): | ||
def __init__(self, a): | def __init__(self, a): | ||
A.__init__(self, a) | A.__init__(self, a) | ||
</pre> | |||
</ | |||
== Abstrakte Klasse == | == Abstrakte Klasse == | ||
< | <pre>class A: | ||
@abstractmethod | @abstractmethod | ||
def process(self): | def process(self): | ||
pass | pass | ||
== Verschachtelte Methoden == | == Verschachtelte Methoden == | ||
< | <pre> | ||
class Example: | class Example: | ||
def scan(self, file): | def scan(self, file): | ||
Zeile 375: | Zeile 198: | ||
def _error(msg): | def _error(msg): | ||
print("line {}: {}\n{}".format(lineNo, msg, line) | print("line {}: {}\n{}".format(lineNo, msg, line) | ||
</ | </pre> | ||
Zeile 381: | Zeile 204: | ||
Damit eine Klasse mit "x in classInstance" angesprochen werden kann, muss es einen Iterator geben. | 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: | Im Beispiel wird dies in einer Klasse zusammengefasst:__iter__() liefert als Iterator sich selbst und __next__() implementiert diesen Iterator: | ||
< | <pre> | ||
class Example: | class Example: | ||
def __init__(): | def __init__(): | ||
Zeile 397: | Zeile 220: | ||
def next(): | def next(): | ||
return self.__next__() | return self.__next__() | ||
</ | </pre> | ||