Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # implements_to_string class decorator that helps implementing classes with __unicode__ or __str__ methods
- # Based on: Steven's suggestions
- 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))
Advertisement
Add Comment
Please, Sign In to add comment