Python extension methods

后端 未结 7 1946
星月不相逢
星月不相逢 2021-02-02 06:39

OK, in C# we have something like:

public static string Destroy(this string s) { 
    return \"\";
}

So basically, when you have a string you ca

7条回答
  •  花落未央
    2021-02-02 07:27

    You can change the built-in classes by monkey-patching with the help of forbidden fruit

    But installing forbidden fruit requires a C compiler and unrestricted environment so it probably will not work or needs hard effort to run on Google App Engine, Heroku, etc.

    I changed the behaviour of unicode class in Python 2.7 for a Turkish i,I uppercase/lowercase problem by this library.

    # -*- coding: utf8 -*-
    # Redesigned by @guneysus
    
    import __builtin__
    from forbiddenfruit import curse
    
    lcase_table = tuple(u'abcçdefgğhıijklmnoöprsştuüvyz')
    ucase_table = tuple(u'ABCÇDEFGĞHIİJKLMNOÖPRSŞTUÜVYZ')
    
    
    def upper(data):
        data = data.replace('i',u'İ')
        data = data.replace(u'ı',u'I')
        result = ''
        for char in data:
            try:
                char_index = lcase_table.index(char)
                ucase_char = ucase_table[char_index]
            except:
                ucase_char = char
            result += ucase_char
        return result
    
    curse(__builtin__.unicode, 'upper', upper)
    class unicode_tr(unicode):
        """For Backward compatibility"""
        def __init__(self, arg):
            super(unicode_tr, self).__init__(*args, **kwargs)
    
    if __name__ == '__main__':
        print u'istanbul'.upper()
    

提交回复
热议问题