I have seen this peice of code in a tutorial regarding Monostate design pattern in Python:
class BookShelf:
_shared_state = {}
def __init__(self, number_of_books):
self.number_of_books = number_of_books
def __new__(cls, *args, **kwargs):
object_ = super().__new__(cls)
object_.__dict__ = cls._shared_state
return object_
When I tested this code, it works as the class addresses are different while the number_of_books is shared between them. I don't understand how the number_of_books is passed to the _shared_state. What I understand from the code is that _shared_state is passed to the new objects' __dict__ attribute. So how is the state actually shared between instances when __dict__ is never passed to _shared_state?!
Aucun commentaire:
Enregistrer un commentaire