Python: Unterschied zwischen den Versionen
Zur Navigation springen
Zur Suche springen
K (→Exception) |
K (→Formatierung) |
||
Zeile 95: | Zeile 95: | ||
"{: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) | ||
</pre> | |||
== Klasse als Sequenz == | |||
Damit eine Klasse mit "x in classInstance" angesprochen werden kann, muss es __iter__() und __next__() geben: | |||
<pre> | |||
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 | |||
</pre> | </pre> |
Version vom 10. März 2017, 12:21 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
- List: ['a', 1]; x[1] = 5; x.insert(0, 'firstItem')
- Tupel: ('a', 1), ro
Spezielle Methoden/Attribute
- Statische Methoden:
class X: @staticmethod def doIt(param): pass X.doIt(True)
- Feststellen, ob Attribut existiert: hasattr(instance, nameOfAttribute)
- dynamischer Code:
exec 'import ' + module
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
Dateien
with open(self._filename, "r") as fp: for line in fp: print line fp.close()
Typcheck
isStringOrSubclass = isinstance(aVariable, str) isString = type(aVariable) is str isList = type([1, 2]) is list isDict = type({ 0:"a", 1:"b" }) is dict
Formatierung
"{:3.7f} {:s} {:07d}".format(3.14, "hello", 100) "{0:d} / {0:x}".format(714)
Klasse als Sequenz
Damit eine Klasse mit "x in classInstance" angesprochen werden kann, muss es __iter__() und __next__() geben:
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