lundi 30 novembre 2015

how make a singleton on python?

please help fix code. i try make pattern singletone:

class Room:
    obj = None 

    def __new__(cls):          
        if cls.obj is None:               
            cls.obj = object.__new__(cls) 
        return cls.obj   

    def __init__(self, left_wall, right_wall, front_wall, back_wall):
        self.left_wall = left_wall
        self.right_wall = right_wall
        self.front_wall = front_wall
        self.back_wall = back_wall

    def __str__(self):
        return str(self.left_wall) + str(self.right_wall) + str(self.front_wall) + str(self.back_wall)


room_obj = Room(True, False, True, True)
print(room_obj)

room_obj2 = Room(True, False, False, True)
print(room_obj2)

print(room_obj is room_obj2)

after I run this code, the console get the following:

kalinin@kalinin ~/python/object2 $ python index.py
TrueFalseTrueTrue
TrueFalseFalseTrue
False

It should not create two objects

Aucun commentaire:

Enregistrer un commentaire