Also
der fertige Work-a-Round geht momentan über __getattr__ ganz gut:
Code: Alles auswählen
import time
class cursor:
def __getattr__(self, attr):
if attr == 'lastrowid':
return self._lastrowid()
return getattr(self._cursor, attr)
def _lastrowid(self):
return time.time()
cursor = cursor()
print cursor.lastrowid
time.sleep(0.3)
print cursor.lastrowid
time.sleep(0.3)
print cursor.lastrowid
Das ganze über property:
Code: Alles auswählen
import time
class cursor:
def _lastrowid(self):
return time.time()
lastrowid = property(_lastrowid)
cursor = cursor()
print cursor.lastrowid
time.sleep(0.3)
print cursor.lastrowid
time.sleep(0.3)
print cursor.lastrowid
Und da wir schon mal dabei sind... Was ist besser, __getattr__ oder property???
Mir erscheint property um einiges einfacher zu sein
EDIT: Mir fällt gerade ein, das es in meinem Fall nicht so einfach mit property gehen wird... Ich würde ja immer das evtl. schon vorhandene .lastrowid überschreiben. Ich müßte also erstmal nach prüfen ob .lastrowid nicht existiert und dann erst mein eigenes implementieren... Aber wie geht das?
Zum anderen, existiert ich in meinem Fall eh ein __getattr__.
EDIT2: So kann es aber doch gehen:
Code: Alles auswählen
import time
class cursor:
def _lastrowid(self):
return time.time()
if not hasattr(cursor, "lastrowid"):
cursor.lastrowid = property(cursor._lastrowid)
c = cursor()
print c.lastrowid
time.sleep(0.3)
print c.lastrowid
time.sleep(0.3)
print c.lastrowid
Ist aber auch nicht so optimal, weil die if-Geschichte auf Modulebene passiert...
Tipps?