【问题标题】:"'int' object has no attribute 'getal'" in self made class Python自制类Python中的“'int'对象没有属性'getal'”
【发布时间】:2017-12-21 08:33:56
【问题描述】:

该程序的想法是采用一种“语言”并将其转化为数字。该语言的构建非常容易

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'

但如果我将自己更改为字符串,我会得到 ​​p>

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

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

谁能帮帮我?

已经非常感谢了

【问题讨论】:

    标签: python string class int


    【解决方案1】:

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

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

    代替:

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

    【讨论】:

    • 很好,它有帮助。顺便说一句,您有权upvote。 ;)
    • 嘿,以前没用,因为我不够“经验”:D
    • 是的,接受答案会给您积分,提高您的声誉,并可能使您超过此限制。
    猜你喜欢
    • 2018-12-02
    • 2015-04-25
    • 1970-01-01
    • 2013-06-13
    • 2014-03-30
    • 2020-04-24
    • 2020-05-25
    • 1970-01-01
    相关资源
    最近更新 更多