Работа с setter и getter в Python

Posted by & filed under python.

class C(object): def __init__(self): self._x = None @property def x(self): «»»I’m the ‘x’ property.»»» return self._x @x.setter def x(self, value): self._x = value @x.deleter def x(self): del self._x Замечание: использовать свойства только с новым типом описания классов: class С(object): А не: class C(): Иначе возникают мистические проблемы с гетерами и сеттерами.

urlparse.parse_qs

Posted by & filed under python.

Распарсинг хвоста урла: import urlparse query=’id=1&address=something’ mydict=urlparse.parse_qs(query) Результат: {‘id’:[1],’address’:[‘something’]}

Работа с timezone в Python

Posted by & filed under python.

from pytz import timezone from datetime import datetime tz = ‘Europe/Moscow’ server_time = datetime.utcnow() client_time = timezone(tz).fromutc(server_time) Дублирующая ссылка на код: http://livepad.ru/view/9229aff1

Ресайз (resize) картинок в Python

Posted by & filed under python.

# resize an image using the PIL image library # free from: http://www.pythonware.com/products/pil/index.htm # tested with Python24 vegaseat 11oct2005 import Image # open an image file (.bmp,.jpg,.png,.gif) you have in the working folder imageFile = «zFlowers.jpg» im1 = Image.open(imageFile) # adjust width and height to your needs width = 500 height = 420 # use… Read more »

Проверка на тип в Python

Posted by & filed under python.

d={} if type(d)==type(dict()): print ‘Its dict!’ else: print ‘Its not dict’ 2 способ (более лучший ИМХО): d={} if type(d) is dict: print ‘Its dict!’ else: print ‘Its not dict’

r=r2={} (олд_скульники, осторожно)

Posted by & filed under python.

Ошибка, которую я сразу и не заметил: r=r2={} Теперь если сделать так r[‘hello’] =’world’ А потом  так: print(r2[‘hello’] ) То получим «world» , так что будьте аккуратны. Определять словари нужно по одному: r={} r2={}

Trace ошибки в Python

Posted by & filed under python.

Странно что Trace ошибки не включен в класс Exceprion и приходится отдельно подключать модуль. Итак, trace ошибки выводится так: import traceback try: raise Exception(‘hi’) except Exception,e: print (traceback.format_exc())

Работа с xpath в Python

Posted by & filed under python.

Простейшая работа: import libxml2 doc=libxml2.parseDoc(content) a=doc.xpathEval(‘/kml/Response/name’) print ((a[0].content)) Работа с учётом namespace: import libxml2 doc=libxml2.parseDoc(content) xp = doc.xpathNewContext() xp.xpathRegisterNs(«kml2», «http://earth.google.com/kml/2.0″) a=xp.xpathEval(‘/kml2:kml/kml2:Response/kml2:name’) print ((a[0].content)) Данный пример работает для следующего xml-файла: <kml xmlns=»http://earth.google.com/kml/2.0″><Response> <name>1600 pennsylvania ave washington dc</name> <Status> <code>200</code> <request>geocode</request> </Status> <Placemark id=»p1″> <address>1600 Pennsylvania Ave NW, Washington D.C., DC 20500, USA</address> <AddressDetails Accuracy=»8″ xmlns=»urn:oasis:names:tc:ciq:xsdschema:xAL:2.0»><Country><CountryNameCode>US</CountryNameCode><CountryName>USA</CountryName><AdministrativeArea><AdministrativeAreaName>DC</AdministrativeAreaName><SubAdministrativeArea><SubAdministrativeAreaName>District of… Read more »