2016-11-30 84 views
3

我有一些问题与Python,所以我的继承人类这一点:Python的“实例没有属性...”

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) 

,当我尝试在这样的另一个类使用方法“中心” :

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". 

我不知道该怎么做了,为什么不把它看我的方法?

+2

您应该编辑您的第一个代码段,以包含如何定义“Rectangle”类的完整性。 – metatoaster

+0

另外,'setUp'不应该包含任何assert *调用。考虑将'assertRaises'移动到它自己的测试方法。 – metatoaster

+0

好的,修好了,谢谢! :) –

回答

2

读取您的代码,看起来您在Rectangle类之外定义了center,这是因为缩进错误。

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

我尝试了正确的缩进,它确实工作。

相关问题