Reassign yourself to init

I have a class that has a lookup dict in the body of the class in which all instances are stored and with some key.

When I instantiate instances, I do not hold them in any variable or in the external dict, I save them in this lookup dict.

When somehow I create an instance that is already in the dict, I reassign it to the dict file and update it using its new and old value in some other function.

Interestingly, is this a good practice? Or should I refactor and make it have an external dict that contains instances.

Is there any PEP benchmark for this behavior?

Example:

class MyClass:
    all_instances = {}  # this dictionary is in local space and it clear that
                        # the only interaction is with MyClass

    def __init__(self, unique_id, x, y, z):
        if unique_id not in MyClass.all_instances:
            self.unique_id = unique_id
            self.x = x
            self.y = y
            self.z = z
            MyClass.all_instances[unique_id] = self
        else:
            self = MyClass.all_instances[unique_id]
            self.update(x, y, z)

    def update(self, new_x, new_y, new_z):
        self.x = self.do_something_with(self.x, new_x)
        self.y = self.do_something_with(self.y, new_y)
        self.z = self.do_something_with(self.z, new_z)

    @staticmethod
    def do_something_with(old_value, new_value):
        # do something with old value and new and return some value
        value = (old_value + new_value) / 2  # more complicated than tht
        return value


while True:
    for id in get_ids():  # fetch ids from some database
        x, y, z = get_values(id)  # fetch values from some other database
        MyClass(id, x, y, z)

, , , , , , .

, , , , .

, :

class MyClass:
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

    def update(self, new_x, new_y, new_z):
        self.x = self.do_something_with(self.x, new_x)
        self.y = self.do_something_with(self.y, new_y)
        self.z = self.do_something_with(self.z, new_z)

    @staticmethod
    def do_something_with(old_value, new_value):
        # do something with old value and new and return some value
        value = (old_value + new_value) / 2  # more complicated than tht
        return value

all_instances = {}  # this dictionary is now in global space
                    # and it unclear if the only interaction is with MyClass
while True:
    for id in get_ids():  # fetch ids from some database
        x, y, z = get_values(id)  # fetch values from some other database
        if id not in all_instances:
            all_instances[id] = MyClass(x, y, z)
        else:
            all_instances[id].update(x, y, z)
+4
2

, , . ( singleton-like, , ). , ( ) - , .

, , , "" , __new__.

class MyClass(object):

    all_instances = {}

    def __new__(cls, unique_id, x, y, z):
        instance = cls.all_instances.get(unique_id)
        if instance is not None:
            instance.is_initialized = True
        else:
            instance = super(MyClass, cls).__new__(cls, unique_id, x, y, z)
            instance.is_initialized = False
        return instance

    def __init__(self, unique_id, x, y, z):
        if self.is_initialized:
            return
        # Do initialization here.

, __new__ . , , . __new__ (object), () MyClass. __new__ ( , MyClass), __init__. , __init__ ( is_initialized.

is_initialized - , reset x, y, z .. , .

+4
result = {}
class abc:
     def __init__(self) : pass
     def update(self,_id,old,new):
          result["res:"+str(_id)] = (old + new)/2.0
     def clean(self,command):
          for e in result.keys():
               if e.startswith("res:"):
                    if command == "to_zero": result[e]= 0
                    elif command == "del": del result[e]
     def read(self,_id):
          if "res:"+_id in result.keys() : return _id,result["res:"+_id]



result["fun"] = abc()

result['fun'].update("hello",8,3)
print result["fun"].read("hello")

>>> 
('hello', 5.5)
>>> 

, - . , Si tacuisses, philosophus mansisses

+1

All Articles