“'int'对象在自制类Python中没有属性'getal'”

时间:2017-12-21 08:33:56

标签: python string class int

该计划的想法是采用“语言”并将其转换为数字。语言很容易构建

  

K = 10   P = 20   T = 40   V = 80   小于10的任何东西都将以正常数字表示

现在这些数字不应该让我担心,我会解释这一点,这样我就可以更容易地得到我想要实现的目标。

我建立了一个名为“Mangarevaans”的课程,如下所示:

def mag2arab(getal):    #this function is designed to turn the letters into the normal numbers we're used to 
mag = str(getal)
waarde = {"K": 10, "P": 20, "T": 40, "V": 80}
arab = 0

for index, j in enumerate(mag):
    if index == 0 and j.isnumeric():

        if len(getal) == 1:
            x = 0
        else:
            x = 1

        arab += int(j) * waarde[mag[x]]
    elif j.isnumeric():
        arab += int(j)
    elif not (str(mag[0]).isnumeric() and index == 1):
        arab += waarde[j]
return arab

class Mangarevaans():
    """
    >>>612 // Mangarevaans(26)
    Mangarevaans('P3')
    """

    def __init__(self, getal):

        if isinstance(getal, int):
            assert 1 <= getal < 799, 'ongeldige waarde'   #this is one of the rules of the language that if there is a number it should be between these values
            self.getal = getal


        else:
            for letter in getal:
                if isinstance(getal, str):
                    for letter in getal:
                        if letter in "VTPK":
                            self.getal = getal
                else:
                    raise AssertionError('ongeldige waarde')
            self.getal = mag2arab(getal)

    def __int__(self):
        return self.getal

    def __str__(self):
        return arab2mag(self.getal)

    def __repr__(self):
        return f"Mangarevaans('{str(arab2mag(self.getal))}')"

    def __rfloordiv__(other, self):
        return Mangarevaans(other // self.getal) #The problem occurs here 

现在我想运行doctest

    """
    >>>612 // Mangarevaans(26)
    Mangarevaans('P3')
    """

我收到错误说

  

'int'对象没有属性'getal'

但如果我将自己改为字符串,我会

  

'str'对象没有属性'getal'

如何定义属性“getal”是否属于“str”或“int”?

任何人都可以帮助我吗?

非常感谢

1 个答案:

答案 0 :(得分:1)

self始终是第一个参数,即使在r*(右)方法中也是如此。所以写:

def __rfloordiv__(self, other):
    return Mangarevaans(other // self.getal)

而不是:

def __rfloordiv__(other, self):
    return Mangarevaans(other // self.getal)