15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Creation time, modification time, and access time are familiar attributes of files, but nothing says that<br />

you cannot add this type of information to objects. After all, certain applications may benefit from these<br />

additional pieces of information.<br />

If you are unfamiliar with using these three pieces of chronological data, we will attempt to clarify them.<br />

The creation time (or "ctime") is the time of instantiation, the modification time (or "mtime") refers to<br />

the time that the core data was updated [accomplished by calling the new set() method], and the<br />

access time (or "atime") is the timestamp of when the data value of the object was last retrieved or an<br />

attribute was accessed.<br />

Proceeding to updating the class we defined earlier, we create the module twrapme.py, given in Example<br />

13.7.<br />

Example 13.7. Wrapping Standard Types (twrapme.py)<br />

Class definition that wraps any built-in type, adding time attributes; get(), set(), and string<br />

representation methods; and delegating all remaining attribute access to those of the<br />

standard type.<br />

1 #!/usr/bin/env python<br />

2<br />

3 from time import time, ctime<br />

4<br />

5 class TimedWrapMe(object):<br />

6<br />

7 def __init__(self, obj):<br />

8 self.__data = obj<br />

9 self.__ctime = self.__mtime = \<br />

10 self.__atime = time()<br />

11<br />

12 def get(self):<br />

13 self.__atime = time()<br />

14 return self.__data<br />

15<br />

16 def gettimeval(self, t_type):<br />

17 if not isinstance(t_type, str) or \<br />

18 t_type[0] not in 'cma':<br />

19 raise TypeError, \<br />

20 "argument of 'c', 'm', or 'a' req'd"<br />

21 return getattr(self, '_%s__%stime' % \<br />

22 (self.__class__.__name__, t_type[0]))<br />

23<br />

24 def gettimestr(self, t_type):<br />

25 return ctime(self.gettimeval(t_type))<br />

26<br />

27 def set(self, obj):<br />

28 self.__data = obj<br />

29 self.__mtime = self.__atime = time()<br />

30<br />

31 def __repr__(self): # repr()<br />

32 self.__atime = time()<br />

33 return 'self.__data'<br />

34<br />

35 def __str__(self): # str()<br />

36 self.__atime = time()<br />

37 return str(self.__data)

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!