如何防止在__init __()python中创建对象

时间:2018-01-06 12:52:36

标签: python oop init

用TDD练习python OOP。以下代码创建了子类室的类办公室对象,即使给出了以数字开头的名称。我该如何预防呢?谢谢大家的帮助

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>)

来自测试用例的结果

{  
 "success":1,
 "results":[  
  {  
     "id":"580395",
     "sport_id":"1",
     "time":"1515232810",
     "time_status":"1",
     "league":{  
        "id":"891",
        "name":"Israel Youth League",
        "cc":"il"
     },
     "home":{  
        "id":"10116",
        "name":"Maccabi Tel Aviv U19",
        "image_id":"222408",
        "cc":"il"
     },
     "away":{  
        "id":"46743",
        "name":"Maccabi Petach Tikva U19",
        "image_id":"240834",
        "cc":"il"
     },
     "ss":"2-1",
     "timer":{  
        "tm":95,
        "ts":26,
        "tt":"1",
        "ta":4
     },
     "scores":{  
        "2":{  
           "home":"2",
           "away":"1"
        },
        "1":{  
           "home":"2",
           "away":"0"
        }
     },
     "stats":{  
        "attacks":[  
           "39",
           "31"
        ],
        "corners":[  
           "8",
           "2"
        ],
        "corner_h":[  
           "5",
           "0"
        ],
        "dangerous_attacks":[  
           "28",
           "22"
        ],

F的

1 个答案:

答案 0 :(得分:4)

阅读之后,得到了答案。 在对象创建期间,在 init 之前调用 new 。因此,通过覆盖 new ,可以控制对象创建。 在我的情况下,我想只创建一个名字以字母开头的房间(办公室)。这就是做了什么:

def __new__(cls,rname):

    '''We need this method since creation of an office object is depended on the first character of its name'''
    if not rname[0].isdigit():
        return Room.__new__(cls, rname)

    else:
        return None #don't create object here. __init__() is not called too.