'int'对象没有属性'x' [英] 'int' object has no attribute 'x'

查看:54
本文介绍了'int'对象没有属性'x'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个使用 __ add __ 来添加向量的程序:

I'm trying to make a program to add vectors using __add __:

class vects:
    def __init__(self,x,y):
        self.x = x
        self.y = y

    def __add__(self, vect):
        total_x = self.x + vect.x
        total_y = self.y + vect.y
        return vects(total_x, total_y)

plusv1 = vects.__add__(2,5)
plusv2 = vects.__add__(1,7)
totalplus = plusv1 + plusv2

产生的错误如下:

line 12, in <module> plusv1 = vects.__add__(2,5)
line 7, in __add__ total_x = self.x + vect.x
AttributeError: 'int' object has no attribute 'x' 

推荐答案

您不会像这样使用 __ add __ !:-)在 Vects 类的实例上使用 + 时,将隐式调用 __ add __ .

You don't use __add__ like that! :-) __add__ will get implicitly invoked when + is used on an instance of the Vects class.

因此,您首先要做的是初始化两个向量实例:

So, what you should first do is initialize two vector instances:

v1 = Vects(2, 5)
v2 = Vects(1, 7)

然后添加它们:

totalplus = v1 + v2

如果添加漂亮的 __ str __ 以获得新矢量的漂亮表示形式,则:

If you add a nice __str__ to get a nice representation of your new vector:

class Vects:
    def __init__(self,x,y):
        self.x = x
        self.y = y

    def __add__(self, vect):
        total_x = self.x + vect.x
        total_y = self.y + vect.y
        return Vects(total_x, total_y)

    def __str__(self):
        return "Vector({}, {})".format(self.x, self.y)

您可以通过打印来获得 totalplus 的视图:

You can get a view of totalplus by printing it:

print(totalplus)
Vector(3, 12)

这篇关于'int'对象没有属性'x'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆