import time ms = int(round(time.time() * 1000)) print(ms)
class A: @staticmethod def m(): print "A" class B(A): @staticmethod def m(): print "B" a = A() a.m() # A b = B() b.m() # B
class A(object): def __init__(self): print "world" class B(A): def __init__(self): print "hello" super(B, self).__init__()
class A: def __init__(self): print "world" class B(A): def __init__(self): print "hello" A.__init__(self)
def equals_ignore_case(s1, s2): if s1 is None and s2 is None: return True if s1 is None and s2 is not None: return False if s1 is not None and s2 is None: return False return s1.lower() == s2.lower()
def contains(dict, key): return key in dict dict={} dict['a']=1 dict['b']=2 dict['c']=3 print(contains(dict, 'a')) # True print(contains(dict, 'd')) # False
if e in list: list.remove(e)
while e in list: list.remove(e)
try: list.remove(e) except ValueError: # not in the list pass
while True: try: list.remove(e) except ValueError: break
Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.
>>> x=1 >>> print x 1 >>> del x >>> print x Traceback (most recent call last): File "", line 1, in NameError: name 'x' is not defined
>>> x=1 >>> print x 1 >>> x=None >>> print x None
class AClass { private int count =0; public synchronized inc(){ count++; } public synchronized dec(){ count--; } }
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
class AClass { private static int _count = 0; public static synchronized inc(){ _count ++; } public static synchronized dec(){ _count --; } }
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
import os os.path.exists('/tmp/1.txt') os.path.exists('/tmp')
import os os.path.isfile('/tmp/1.txt')
import os os.path.abspath('abc/abc.txt')
s='abc' print(s.index('b')) # 1 print(s.find('b')) # 1 print(s.find('d')) # -1 print(s.index('d')) # exception
with open('myfile.txt') as f: return [line for line in f if len(line)>80]
class Iterator(object): def next(self): pass class Iterable(object): def __iter__(self): return Iterator()
class AClass(object): def __init__(self): self._list = [1,2,3] def __len__(self): return len(self._list) a=AClass() print(a.__len__()) # 3 print(len(a)) # 3
import zlib import sys import urllib2 def __zlib_csum(url, func): if isinstance(url, basestring if sys.version_info[0] < 3 else str): url = urllib2.Request(url) f = urllib2.urlopen(url) csum = None try: chunk = f.read(1024) if len(chunk)>0: csum = func(chunk) while True: chunk = f.read(1024) if len(chunk)>0: csum = func(chunk, csum) else: break finally: f.close() if csum is not None: csum = csum & 0xffffffff return csum def crc32(url): return __zlib_csum(url, zlib.crc32) def adler32(url): return __zlib_csum(url, zlib.adler32) if __name__ == '__main__': print(hex(crc32('file:/tmp/111.zip'))) print(hex(adler32('file:/tmp/111.zip')))
class Animal: DOG = 1 CAT = 2 x = Animal.DOGor
class Animal: DOG, CAT = range(2) x = Animal.DOG
class Animal(Enum): DOG = 1 CAT = 2 x = Animal.DOGor equivalently:
from enum import Enum Animal = Enum('Animal', 'DOG CAT') x = Animal.DOG