[Tutor] class decorator question
Alan Gauld
alan.gauld at btinternet.com
Sun Oct 6 02:06:18 CEST 2013
On 05/10/13 20:26, Albert-Jan Roskam wrote:
> General question: I am using pastebin now. Is that okay,
For code as short as this it's probably best kept with the message.
But once you get to 100+ lines its more debatable and if you get
to 200+ lines I'd definitely say a pastebin is better.
> from __future__ import print_function
> import sys
>
> def decorate(cls):
> print("decorate called")
> if sys.version_info[0] > 2:
> cls.__dict__["__str__"].__name__ = '__bytes__'
> cls.__dict__["__unicode__"].__name__ = '__str__'
> cls.__bytes__ = cls.__dict__["__str__"]
> cls.__str__ = cls.__dict__["__unicode__"]
> return cls
>
> @decorate
> class Test(object):
>
> def __init__(self):
> self.__dict__["encoding"] = self.encoding
>
> def __str__(self):
> return "str called".encode(self.encoding)
>
> def __unicode__(self):
> return "unicode called"
>
> @property
> def encoding(self):
> """In reality this method extracts the encoding from a file"""
> return "utf-8" # rot13 no longer exists in Python3
>
> if __name__ == "__main__":
> t = Test()
> if sys.version_info[0] == 2:
> print(unicode(t))
> print(str(t))
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list