From 9bfa30246b473b4c2cdb72aca79d9182b1f21325 Mon Sep 17 00:00:00 2001 From: Anirudha Bose Date: Fri, 11 Aug 2017 00:55:22 +0200 Subject: [PATCH] Fix design pattern examples --- .gitignore | 2 ++ examples/flyweight.py | 9 ++++----- examples/prototype.py | 2 +- examples/singleton.py | 11 +++++------ reobject/models/model.py | 6 +++++- 5 files changed, 17 insertions(+), 13 deletions(-) diff --git a/.gitignore b/.gitignore index 96df849..d3a8e8b 100644 --- a/.gitignore +++ b/.gitignore @@ -179,3 +179,5 @@ pyvenv.cfg pip-selfcheck.json # End of https://www.gitignore.io/api/python,pycharm,linux,virtualenv + +README.rst diff --git a/examples/flyweight.py b/examples/flyweight.py index 2ea1ecc..2e60426 100644 --- a/examples/flyweight.py +++ b/examples/flyweight.py @@ -2,12 +2,12 @@ import unittest -from reobject.models.model import Model +from reobject.models import Model, Field class Card(Model): - def __init__(self, suit, color): - self.suit, self.color = suit, color + suit = Field() + color = Field() class TestCard(unittest.TestCase): @@ -27,8 +27,7 @@ def test_flyweight(self): c1.delete() self.assertEqual(Card.objects.count(), 1) - c2.delete() - self.assertEqual(Card.objects.count(), 1) + self.assertNotIn(c2, Card.objects.all()) c3.delete() self.assertEqual(Card.objects.count(), 0) diff --git a/examples/prototype.py b/examples/prototype.py index d10f4fa..733030e 100644 --- a/examples/prototype.py +++ b/examples/prototype.py @@ -3,7 +3,7 @@ import unittest from copy import deepcopy -from reobject import Model +from reobject.models import Model class Prototype(Model): diff --git a/examples/singleton.py b/examples/singleton.py index 6ce36eb..9152516 100644 --- a/examples/singleton.py +++ b/examples/singleton.py @@ -2,18 +2,17 @@ import unittest -from reobject import Model +from reobject.models import Model, Field class Singleton(Model): - def __init__(self, value=None): - self.value = value + value = Field(default=None) def __new__(cls, *args, **kwargs): - if Singleton.objects.count(): - return Singleton.objects.get() + if cls.objects.count() == 0: + return super().__new__(cls) else: - return super().__new__(cls, *args, **kwargs) + return cls.objects.get() class TestSingleton(unittest.TestCase): diff --git a/reobject/models/model.py b/reobject/models/model.py index c90ae8a..67b3dc2 100644 --- a/reobject/models/model.py +++ b/reobject/models/model.py @@ -18,7 +18,11 @@ def __new__(cls, name, bases, attrs): class Model(object, metaclass=ModelBase): def __attrs_post_init__(self): - return type(self).objects._add(self) + pass + + def __new__(cls, *args, **kwargs): + instance = super(Model, cls).__new__(cls) + return cls.objects._add(instance) @property def id(self) -> int: