【发布时间】:2018-01-06 12:52:36
【问题描述】:
我正在使用 TDD 练习 python OOP。以下代码正在创建子教室的班级办公室对象,即使给定以数字开头的名称。我该如何预防?谢谢大家帮忙
class Room(object):
"""Create general features of a general room
Each room has a certain capacity depending on its type(an office or a living room)
"""
def __init__(self):
super(Room, self).__init__()
self.capacity = '';
class Office(Room):
"""
Add specific features to make a room an office.
An office has a name and a space for maximum of 4 people.
"""
def __init__(self, rname):
#create object if name does not start with a digit
if not (rname[0].isdigit()):
super(Office,self).__init__()
self.name = rname #office name
self.capacity = 4 #number of spaces per office
这是测试用例:
class OfficeTests(unittest.TestCase):
def setUp(self):
self.office = Office('BLUE')
self.office1 = Office('12345')
def test_office_is_of_class_office(self):
self.assertTrue(isinstance(self.office, Office),
msg = "Should create an object of class Office")
def test_office_is_of_class_room(self):
self.assertTrue(isinstance(self.office, Room),
msg = "Should create an object of class Office of subclass Room")
def test_office_capacity_is_4(self):
self.assertEqual(self.office.capacity, 4,
msg= "An office has a maximum of 4 ")
def test_office_has_a_name(self):
self.assertEqual(self.office.name,'BLUE', msg = "Should assign name to an office created.")
def test_office_name_does_not_start_with_a_digit(self):
print(self.office1, self.office)
self.assertTrue(self.office1 == None, msg = "Office name can only start with a letter.")
def tearDown(self):
self.office = None
以及测试用例的结果
....(<room.Office object at 0x7fa84dc96a10>, <room.Office object at 0x7fa84dc968d0>)
F...
【问题讨论】:
-
抛出异常。
-
当名称以数字开头时可以引发异常
-
引发异常是唯一的解决方案吗?
-
@MeshackMbuvi 不,您可以使用
__new__阻止创建对象。