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> | ||
import re | import re | ||
rexpr = re.compile(r"([\da-z]+)") | rexpr = re.compile(r"([\da-z]+)") | ||
Zeile 27: | Zeile 23: | ||
if match != None: | if match != None: | ||
number = (int) rexpr.group(1) | number = (int) rexpr.group(1) | ||
</pre> | |||
</ | |||
= Datentypen = | = Datentypen = | ||
Zeile 46: | Zeile 35: | ||
# 2-stellig mit führender 0 ausgeben: | # 2-stellig mit führender 0 ausgeben: | ||
f'{sec//3600}:{sec%3600//60:02}:{sec%60:02}' | f'{sec//3600}:{sec%3600//60:02}:{sec%60:02}' | ||
</syntaxhighlight> | </syntaxhighlight> | ||
* str.format() | * str.format() | ||
Zeile 81: | Zeile 66: | ||
== Dictionary== | == Dictionary== | ||
< | <pre> | ||
x = { 'key' : 'val', 'xyz': 3 } | x = { 'key' : 'val', 'xyz': 3 } | ||
x['key'] = value | x['key'] = value | ||
Zeile 87: | Zeile 72: | ||
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 84: | ||
== 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 94: | ||
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) | ||
Zeile 150: | Zeile 127: | ||
diffSec = (date1 - date2).total_seconds() | diffSec = (date1 - date2).total_seconds() | ||
diffDays = (date1 - date2).days | diffDays = (date1 - date2).days | ||
</ | </pre> | ||
== Enum == | == Enum == | ||
< | <pre>from enum import Enum | ||
from enum import Enum | |||
class TokenType(Enum): | class TokenType(Enum): | ||
digit = 1 ; string = 2 ; id = 3 ; operator = 4 | digit = 1 ; string = 2 ; id = 3 ; operator = 4 | ||
Zeile 172: | Zeile 137: | ||
for item in TokenType: | for item in TokenType: | ||
print(item.name) | print(item.name) | ||
</ | </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 158: | ||
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 178: | ||
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 187: | ||
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 = | ||
== Sortieren == | == Sortieren == | ||
< | <pre>a =["Joe", "Eve", "Bob", "alma", "Adam"] | ||
a =["Joe", "Eve", "Bob", "alma", "Adam"] | |||
a.sort() | a.sort() | ||
# sort by a global function: | # sort by a global function: | ||
Zeile 251: | Zeile 197: | ||
# sort by a lambda function which calculates the sorting key: | # sort by a lambda function which calculates the sorting key: | ||
a.sort(key=lambda x: x[2]) | a.sort(key=lambda x: x[2]) | ||
</pre> | |||
</ | |||
== 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, open(self._input, "r") as fpInp: | with open(self._filename, "w") as fp, open(self._input, "r") as fpInp: | ||
line = fpInp.read() | line = fpInp.read() | ||
fp.write(line); | fp.write(line); | ||
</ | </pre> | ||
= Sprachbesonderheiten = | = Sprachbesonderheiten = | ||
== | == Typinfo == | ||
< | <pre> | ||
Vector = list[float] | Vector = list[float] | ||
def sqr(x: float) -> float: | def sqr(x: float) -> float: | ||
return x*x | return x*x | ||
def printName(name: str) -> None: | def printName(name: str) -> None: | ||
print(name); | print(name); | ||
</pre> | |||
</ | |||
== 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) | ||
def asString(self): | def asString(self): | ||
return 'B: ' + super().asString | return 'B: ' + super().asString | ||
</ | </pre> | ||
== Abstrakte Klasse == | == Abstrakte Klasse == | ||
< | <pre>class A: | ||
@abstractmethod | @abstractmethod | ||
def process(self): | def process(self): | ||
pass | pass | ||
</ | </pre> | ||
== Verschachtelte Methoden == | == Verschachtelte Methoden == | ||
< | <pre> | ||
class Example: | class Example: | ||
def scan(self, file): | def scan(self, file): | ||
Zeile 375: | Zeile 262: | ||
def _error(msg): | def _error(msg): | ||
print("line {}: {}\n{}".format(lineNo, msg, line) | print("line {}: {}\n{}".format(lineNo, msg, line) | ||
</ | </pre> | ||
Zeile 381: | Zeile 268: | ||
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 284: | ||
def next(): | def next(): | ||
return self.__next__() | return self.__next__() | ||
</ | </pre> | ||
== Generator == | == Generator == | ||
* einfach mindestens ein "yield <value>" in die Funktion einfügen | * einfach mindestens ein "yield <value>" in die Funktion einfügen | ||
* Bei Rekursion: yield from <method_call> | * Bei Rekursion: yield from <method_call> | ||
< | <pre>def nextFile(directory) | ||
for node in os.listdir(directory): | for node in os.listdir(directory): | ||
full = directory + os.sep + node | full = directory + os.sep + node | ||
Zeile 408: | Zeile 295: | ||
if os.path.isdir(full): | if os.path.isdir(full): | ||
yield from nextFile(full) | yield from nextFile(full) | ||
</ | </pre> | ||
== Unittests == | == Unittests == | ||
< | <pre> | ||
import unittest | import unittest | ||
import sim_parser as sim | import sim_parser as sim | ||
Zeile 425: | Zeile 312: | ||
if __name__ == "__main__": | if __name__ == "__main__": | ||
unittest.main() | unittest.main() | ||
</ | </pre> | ||
== ArgParse == | == ArgParse == |