首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何防止__init__() python中的对象创建

如何防止__init__() python中的对象创建
EN

Stack Overflow用户
提问于 2018-01-06 12:52:36
回答 1查看 1.3K关注 0票数 3

我正在用TDD练习python。下面的代码是创建子类房间的类office的对象,即使给定了一个以数字开头的名称。我该怎么预防呢?谢谢大家的帮助

代码语言:javascript
运行
复制
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

这是一个测试案例:

代码语言:javascript
运行
复制
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

以及测试结果

代码语言:javascript
运行
复制
....(<room.Office object at 0x7fa84dc96a10>, <room.Office object at 0x7fa84dc968d0>)

F..。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-01-06 13:56:18

看了很多书后,得到了答案。在对象创建期间,init.Thus之前被调用,方法是重写--可以控制对象创建。在我的例子中,我只想创建一个以字母开头的房间(办公室)。这就是所做的:

代码语言:javascript
运行
复制
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.
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48127540

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档