Wrapping Standard Types : method « Class « Python Tutorial






#!/usr/bin/env python

from time import time, ctime

class TimedWrapMe(object):

   def __init__(self, obj):
      self.__data = obj
      self.__ctime = self.__mtime = self.__atime = time()

   def get(self):
      self.__atime = time()
      return self.__data

   def gettimeval(self, t_type):
      if not isinstance(t_type, str)  or t_type[0]  not in 'cma':
          raise TypeError, "argument of 'c', 'm', or 'a' req'd"
      return getattr(self, '_%s__%stime' % (self.__class__.__name__, t_type[0]))

   def gettimestr(self, t_type):
       return ctime(self.gettimeval(t_type))

   def set(self, obj):
       self.__data = obj
       self.__mtime = self.__atime = time()

   def __repr__(self):                # repr()
       self.__atime = time()
       return 'self.__data'

   def __str__(self):                 # str()
       self.__atime = time()
       return str(self.__data)

   def __getattr__(self, attr):       # delegate
       self.__atime = time()
       return getattr(self.__data, attr)

          

t = TimedWrapMe(932)
print t.gettimestr('c')
print t.gettimestr('m')
print t.gettimestr('a')
print t
print t.gettimestr('c')
print t.gettimestr('m')
print t.gettimestr('a')

t.set('time is up!')
print t.gettimestr('m')
print t
print t.gettimestr('c')
print t.gettimestr('m')
print t.gettimestr('a')








11.4.method
11.4.1.Methods in class
11.4.2.Intermediate Customization
11.4.3.Any Number of Items Iterator
11.4.4.__str__, __add__, __mul__,__nonzero__,__norm_cval,__cmp__
11.4.5.Wrapping Standard Types
11.4.6.The property() built-in function can take up to four arguments.
11.4.7.A setter
11.4.8.stick in a documentation string for your attribute
11.4.9.Here is our modified class inspired by the recipe:
11.4.10.Class Time with accessor methods.
11.4.11.Methods calling
11.4.12.Add method to a class from outside