Python字符串重载器的十六进制转换器

时间:2018-03-02 23:27:44

标签: python string hex operator-overloading

我正在创建一个十六进制转换器类,它需要一个字符串运算符而不是加载器。当我针对我的实际程序运行测试程序时,str()会使程序崩溃。我尝试打印出实际的字符串以查看我出错的地方,但所有打印的都是空行。测试程序给我一个90.0 / 100.0,因为字符串over loader无法正常工作。 Python code for hex convertor. Updated Code:

class Hexadecimal:
    def __init__(self, decimal = "1128"):
        if type(decimal) is int:
            if decimal >= 0:
                self.__decimal = decimal
            else:
                raise ValueError ("Must be greater than zero.")
        elif type(decimal) is list:
            raise ValueError ("Cannot enter lists.")
        elif type(decimal) is float:
            decimal = int(decimal)
            if decimal >= 0:
                self.__decimal = decimal
            else:
                raise ValueError ("Cannot have negative floats.")

        elif type(decimal) is str:

            if decimal not in ["A", "B", "C", "D", "E", "F"]:  
                decimal = float(decimal)
            else:
                raise ValueError ("Cannot convert string to float.")

        else:
            self.__decimal = int(decimal)


    #Overloaded string function      
    def __str__(self):
        h_string = ""
        number = self.__decimal
        while number > 0:
            digit = number % 16
            number //= 16

            if digit < 10 and digit > 0:
                h_string += str(digit) 


            elif digit == 10:
                h_string += "A"


            elif digit == 11:
                h_string += "B"

            elif digit == 12:
                h_string += "C"

            elif digit == 13:
                h_string += "D"

            elif digit == 14:
                h_string += "E"

            elif digit == 15:
                h_string += "F"




            print(h_string[::-1])
        return h_string[::-1]

结果: 测试str()时崩溃了。 一个 一个 F F 一个 一个 2 32 2 32 一个 一个 9 19 9 19 3 3 1 1 4 4 2 2 4 4 1 1 90.0

0 个答案:

没有答案