Pages

Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Tuesday, December 23, 2014

synchronized method in python








Java code

class AClass {
    private int count =0;

    public synchronized inc(){
        count++;
    }

    public synchronized dec(){
        count--;
    }
}

Python code

import threading

class AClass(object):
    def __init__(self):
        self.__count = 0;
        self.__lock = threading.RLock()

    def inc(self):
        with self.__lock:
            self.__count += 1

    def dec(self):
        with self.__lock:
            self.__count -= 1


see also




synchronized static method in python








Java code

class AClass {
    private static int _count = 0;

    public static synchronized inc(){
        _count ++;
    }
    
    public static synchronized dec(){
        _count --;
    }
}

Python code

import threading

class AClass(object):
    __count = 0
    __lock = threading.RLock()

    @classmethod
    def inc(cls):
        with cls.__lock:
            cls.__count += 1

    @classmethod
    def dec(cls):
        with cls.__lock:
            cls.__count -= 1



Saturday, April 19, 2014

Python: equivalent to Java toString()








In Java, overrides toString() method in the your class can change the textual representation of the object. The equivalent in Python is __str__ and __repr__. The important differences are:
  • the goal of __repr__ is to be unambiguous
  • the goal of __str__ is to be human-readable.
  • str(object) calls the object's __str__ method
  • repr(object) calls the object's __repr__ method
  • by default, if __repr__ is defined and __str__ is not, calls to __str__ will be redirected to __repr__
  • __repr__: representation of python object usually eval will convert it back to that object
  • __str__: is whatever you think is that object in text form
  • str(list) calls the list elements' _repr_ methods. Therefore, to make a list of objects human-readable, you need to override __repr__, or use list comprehension like:
    [str(elem) for elem in list]
    ..

see also