python "instance has no attribute ..."

标签 python methods attributes

我在使用 Python 时遇到了一些问题,所以这是我的类(class):

class Rectangle:

def __init__(self, x1=0, y1=0, x2=0, y2=0):
    if(x1 > x2):
        raise ValueError("x1 cannot be bigger than x2!")
    if(y1 > y2):
        raise ValueError("y1 cannot be bigger than y2!")
    self.pt1 = Point(x1, y1)
    self.pt2 = Point(x2, y2)

def __str__(self):      
    return str("[(" + str(self.pt1.x) + ", " + str(self.pt1.y) + "), (" + str(self.pt2.x) + ", " + str(self.pt2.y) + ")]")

def __repr__(self):        
    return str("Rectangle(" + str(self.pt1.x) + ", " + str(self.pt1.y) + ", " + str(self.pt2.x) + ", "+ str(self.pt2.y) + ")")

def __eq__(self, other): 
    return (self.pt1== other.pt1 and self.pt2 == other.pt2)

def __ne__(self, other):       
    return not self == other

def center(self):         
    return Point((self.pt2.x - self.pt1.x) / 2, (self.pt2.y - self.pt1.y) / 2)

当我尝试在另一个类中使用方法“center”时:

class TestRectangle(unittest.TestCase):

    def setUp(self):
        self.first = Rectangle(1, 2, 3, 4)
        self.second = Rectangle(2, 2, 4, 5)

    def test_init(self):
        with self.assertRaises(ValueError):
            Rectangle(5, 1, 2, 3)
        self.assertEqual(self.first.pt1, Point(1, 2))
        self.assertEqual(self.first.pt2, Point(3, 4))
        self.assertEqual(self.second.pt1.x, 2)      

    def test_str(self):
        self.assertEqual(str(self.first), "[(1, 2), (3, 4)]")

    def test_repr(self):
        self.assertEqual(repr(self.first), "Rectangle(1, 2, 3, 4)")

    def test_eq(self):
        self.assertTrue(self.first == Rectangle(1,2,3,4))
        self.assertFalse(self.first == self.second)

    def test_ne(self):
        self.assertFalse(self.first != Rectangle(1,2,3,4))
        self.assertTrue(self.first != self.second)

    def test_center(self):
        self.assertEqual(self.first.center(), Point(2, 2.5))

我收到这条消息:

Rectangle instance has no attribute "center". 

我现在不知道怎么办,为什么它看不到我的方法?

最佳答案

阅读您的代码,由于缩进错误,您似乎在 Rectangle 类之外定义了 center

因此,Rectangle 实例没有任何center 方法。

我尝试了正确的缩进,它确实有效。

关于 python "instance has no attribute ...",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40878575/

相关文章:

java - 是否可以更改java中继承类的 protected 变量?

java - vector 、点、战舰、2D

c# - 如何检查字符串数组是否包含特定字符串?

C# 属性或特性

python - tensorflow /keras中批量大小的自定义损失w权重数组

python - 来自 Ansible 自定义模块的调试信息?

python - 将函数应用于 python-pandas 中的数据框时出现 ValueError

python - 如何使用 python 从公共(public)谷歌表中获取数据?

java - 为什么方法使用类名作为修饰符(?)和参数?

css - 如何在具有属性的部分中设置类 (css) 的样式