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]]
= Links =
* [[Jupyter]]
* https://www.python.org/downloads/windows/
= Exception =
= Exception =
<syntaxhighlight lang="python">
<pre>
try:
try:
   raise Exception("not allowed")
   raise Exception("not allowed")
Zeile 18: Zeile 14:
finally:
finally:
   closeIt()
   closeIt()
</syntaxhighlight>
</pre>


= Regular Expression =
= Regular Expression =
<syntaxhighlight lang="python">
<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)
# Replacement:
</pre>
regex = re.compile(r"A\d+", re.IGNORECASE)
for line in some_file:
    other = regex.sub('<Id>', line)
# Replacement mit Referenzen:
s = 'aaa@xxx.com bbb@yyy.net ccc@zzz.org'
re.sub('([a-z]+)@([a-z]+)', r'\2@\1', s)
</syntaxhighlight>


= Datentypen =
= Datentypen =
== String ==
== String ==
* "x" und 'x' sind gleichwertig
* "x" und 'x' sind gleichwertig
=== Formatierung ===
* Formatierung
* f-String
** f-String
<syntaxhighlight lang="python">
<syntaxhighlight lang="python">
# Gleitpunktzahl mit 3 Stellen ausgeben:
# Gleitpunktzahl mit 3 Stellen ausgeben:
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}'
# String linksbündig:
f'{data:<10}'
# String rechtsbündig:
f'{data:>10}'
</syntaxhighlight>
</syntaxhighlight>
* str.format()
** str.format()
<syntaxhighlight lang="python">
<syntaxhighlight lang="python">
"{: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)
precision=2
'{:.Pf}'.replace('P', str(precision)).format(value)
</syntaxhighlight>
</syntaxhighlight>
* Bytes -> String: b'data'.decode("utf-8")
* Bytes -> String: b'data'.decode("utf-8")
Zeile 81: Zeile 64:


== Dictionary==
== Dictionary==
<syntaxhighlight lang="python">
<pre>
x = { 'key' : 'val', 'xyz': 3 }
x = { 'key' : 'val', 'xyz': 3 }
x['key'] = value
x['key'] = value
Zeile 87: Zeile 70:
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 key, value in x.items():
for pair in x.iteritems():
   print(key, value)
   key = pair[0]
for key in x:
for key in x.iterkeys():
   print key
   print key
</syntaxhighlight>
</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 82:


== Mengen ==
== Mengen ==
<syntaxhighlight lang="python">
<pre>
s = {3, 'sjoerd'}
s = set(['y', 3]) ; f = frozenset(['y', 3])  
s = {c for c in 'abracadabra' if c not in 'abc'}
assertEquals(s, {'d', 'r'})
iterable = ['y', 3];
s = set(iterable) ;  
f = frozenset(iterable)
s.add(9)
s.remove(9)  
for elem in s:
for elem in s:
   print elem
   print elem
Zeile 116: Zeile 92:
isPartOf = s <= f
isPartOf = s <= f
diff = s - f
diff = s - f
</syntaxhighlight>
</pre>


== Datum/Zeit ==
== Datum/Zeit ==
<syntaxhighlight lang="python">
<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 125:
diffSec = (date1 - date2).total_seconds()
diffSec = (date1 - date2).total_seconds()
diffDays = (date1 - date2).days
diffDays = (date1 - date2).days
</syntaxhighlight>
</pre>
 
=== Leistungsmessung ===
<syntaxhighlight lang="python">
import timeit
body = '''text = 'abcdefg'
s = list(text)
s[6] = 'W'
''.join(s)
'''
print(timeit.timeit(body, number=1000000))
</syntaxhighlight>


== Enum ==
== Enum ==
<syntaxhighlight lang="python">
<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


x = TokenType.id
x = TokenType.id
for item in TokenType:
</pre>
  print(item.name)
</syntaxhighlight>


== Typcheck ==
== Typcheck ==
<syntaxhighlight lang="python">
<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
</syntaxhighlight>
</pre>


== Spezielle Methoden/Attribute ==
== Spezielle Methoden/Attribute ==
* Statische Methoden:
* Statische Methoden:
<syntaxhighlight lang="python">
<pre>
class X:
class X:
   # statische Variable
   # statische Variable
Zeile 193: Zeile 154:


X.add("new")
X.add("new")
</syntaxhighlight>
</pre>
* Feststellen, ob Attribut existiert: hasattr(instance, nameOfAttribute)
* Feststellen, ob Attribut existiert: hasattr(instance, nameOfAttribute)
* dynamischer Code:
* dynamischer Code:
<syntaxhighlight lang="python">
<pre>
exec 'import ' + module
exec 'import ' + module
</syntaxhighlight>
</pre>
* Vollständige Kopie (deep copy):
* Vollständige Kopie (deep copy):
<syntaxhighlight lang="python">
<pre>
import copy
import copy
x = [1, 2]
x = [1, 2]
y = copy.deepcopy(x)
y = copy.deepcopy(x)
</syntaxhighlight>
</pre>
* Superclass-Konstruktor:
* Superclass-Konstruktor:
<syntaxhighlight lang="python">
<pre>
class Parent:
class Parent:
   def __init__(self, name)
   def __init__(self, name)
Zeile 213: Zeile 174:
   def __init__(self, name):
   def __init__(self, name):
       Parser.__init__(self, name)
       Parser.__init__(self, name)
</syntaxhighlight>
</pre>


== Funktionale Programmierung ==
== Funktionale Programmierung ==
<syntaxhighlight lang="python">
<pre>
import functools, math
import functools, math
array = [ 1, 9, 7, 5 ]
array = [ 1, 9, 7, 5 ]
Zeile 222: Zeile 183:
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))
</syntaxhighlight>
</pre>


= Typische Situationen =
= Typische Situationen =
== Division Integer ==
<syntaxhighlight lang="python">
pairs = count // 2
</syntaxhighlight>
== Objekte kopieren (Shallow/Deep Copy) ==
<syntaxhighlight lang="python">
import copy
a = [1, 2, 3]
b = copy.copy(a)
c = [a, [1, 2, 3]]
d = copy.deepcopy(c)
# Speziell bei Listen (shallow copy):
copied_list = original_list[:]
</syntaxhighlight>
== Sortieren ==
== Sortieren ==
<syntaxhighlight lang="python">
<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 193:
# 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])
# 2-stufig: nach Länge absteigend, dann alphabetisch:
</pre>
a.sort(key=lambda x: (-len(x), x))
# comparism function:
def mySort(a, b): return len(a) - len(b)
import functools
a.sort(key=functools.cmp_to_key(mySort))
</syntaxhighlight>


== Externes Programm aufrufen ==
== Externes Programm aufrufen ==
<syntaxhighlight lang="python">
<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())
</syntaxhighlight>
</pre>


== Dateien ==
== Dateien ==
* Lesen:
* Lesen:
<syntaxhighlight lang="python">
<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
</syntaxhighlight>
</pre>
* Binärdatei:
<syntaxhighlight lang="python">
with open(self._filename, "rb") as fp:
  data = fp.read(8000)
  while data:
    doIt(data)
    data = fp.read(8000)
</syntaxhighlight>
 
* Schreiben:
* Schreiben:
<syntaxhighlight lang="python">
<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);
</syntaxhighlight>
</pre>


= Sprachbesonderheiten =
= Sprachbesonderheiten =
== Variable Zahl Parameter in Methode: Liste ==
== Typinfo ==
<syntaxhighlight lang="python">
<pre>
# numbers ist eine Liste:
def find_sum(*numbers):
    result = 0
    for num in numbers:
        result = result + num
   
    print("Sum = ", result)
 
# function call with 3 arguments
find_sum(1, 2, 3)
</syntaxhighlight>
 
== Variable Zahl Parameter in Methode: Map ==
<syntaxhighlight lang="python">
# numbers ist eine Liste:
def show(**params):
    result = 0
    for name,value in params.items():
        print(f'{name}: {value}')
 
# function call with 3 arguments
show(jonny="admin", berta="user")
</syntaxhighlight>
 
== Reflection ==
<syntaxhighlight lang="python">
class A:
  def __init__(self):
    self._a = 0
  def asString(self):
    return 'A'
a = A()
assertTrue(hasattr(a, '_a'));
assertTrue(hasattr(a, 'asString'));
assertFalse(hasattr(a, 'b'));
</syntaxhighlight>
 
== Type Hints ==
<syntaxhighlight lang="python">
from typing import List, Sequence, Mapping
Vector = list[float]
Vector = list[float]
def sqr(x: float) -> float:
def sqr(x: float) -> float:
   return x*x
   return x*x
def first(items: Sequence[str]) -> str:
  return items[0]
def printName(name: str) -> None:
def printName(name: str) -> None:
   print(name);
   print(name);
def evalMap(map: Mapping[int, str]):
</pre>
  return map[3] == 'Hello'
</syntaxhighlight>


== Aufruf Superclass-Konstruktor ==
== Aufruf Superclass-Konstruktor ==
<syntaxhighlight lang="python">class B (A):
<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
</syntaxhighlight>
</pre>


== Abstrakte Klasse ==
== Abstrakte Klasse ==
<syntaxhighlight lang="python">class A:
<pre>class A:


@abstractmethod
@abstractmethod
def process(self):
def process(self):
   pass
   pass
</syntaxhighlight>
</pre>


== Verschachtelte Methoden ==
== Verschachtelte Methoden ==
<syntaxhighlight lang="python">
<pre>
class Example:
class Example:
   def scan(self, file):
   def scan(self, file):
Zeile 375: Zeile 258:
       def _error(msg):
       def _error(msg):
         print("line {}: {}\n{}".format(lineNo, msg, line)
         print("line {}: {}\n{}".format(lineNo, msg, line)
</syntaxhighlight>       
</pre>       
          
          


Zeile 381: Zeile 264:
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:
<syntaxhighlight lang="python">
<pre>
class Example:
class Example:
   def __init__():
   def __init__():
Zeile 397: Zeile 280:
   def next():
   def next():
     return self.__next__()
     return self.__next__()
</syntaxhighlight>
</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>
<syntaxhighlight lang="python">def nextFile(directory)
<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 291:
   if os.path.isdir(full):
   if os.path.isdir(full):
     yield from nextFile(full)
     yield from nextFile(full)
</syntaxhighlight>
</pre>


== Unittests ==
== Unittests ==
<syntaxhighlight lang="python">
<pre>
import unittest
import unittest
import sim_parser as sim
import sim_parser as sim
Zeile 425: Zeile 308:
if __name__ == "__main__":  
if __name__ == "__main__":  
     unittest.main()
     unittest.main()
</syntaxhighlight>
</pre>


== ArgParse ==
== ArgParse ==

Bitte kopiere keine Webseiten, die nicht deine eigenen sind, benutze keine urheberrechtlich geschützten Werke ohne Erlaubnis des Urhebers!
Du gibst uns hiermit deine Zusage, dass du den Text selbst verfasst hast, dass der Text Allgemeingut (public domain) ist, oder dass der Urheber seine Zustimmung gegeben hat. Falls dieser Text bereits woanders veröffentlicht wurde, weise bitte auf der Diskussionsseite darauf hin. Bitte beachte, dass alle Info-Theke-Beiträge automatisch unter der „Gemeinfreiheit“ stehen (siehe Info-Theke:Urheberrechte für Einzelheiten). Falls du nicht möchtest, dass deine Arbeit hier von anderen verändert und verbreitet wird, dann klicke nicht auf „Seite speichern“.

Abbrechen Bearbeitungshilfe (wird in einem neuen Fenster geöffnet)