Article View: pl.comp.lang.python
Article #26985Re: dyskryptory
From: sacre
Date: Sat, 28 Nov 2009 12:40
Date: Sat, 28 Nov 2009 12:40
65 lines
2760 bytes
2760 bytes
De(y)skryptory są osobnymi klasami a ich instancje przypisuje się do
atrybutów klas (przykład mam nadzieje wyjaśni co chciałem powiedzieć :) ).
Jeśli chcesz nauczyć się używania deskryptorów to polecam:
http://users.rcn.com/python/download/Descriptor.htm
A ty przykład:
# tak dla uproszczenia
addr2int = int
int2addr = str
class IpFieldDescriptor(object):
""" klasa deskryptora """
def __init__(self, int_field_name):
self.int_field_name = int_field_name
def __get__(self, obj, cls):
""" konwersja ze string do int """
assert obj is not None,'access only from instance!'
ip_int = getattr(obj, self.int_field_name, None)
if ip_int is not None:
return int2addr(ip_int)
def __set__(self, obj, value):
""" konwersja z int do string """
assert obj is not None,'access only from instance!'
ip_int = addr2int(value)
setattr(obj, self.int_field_name, ip_int)
class IpRange(object):
""" wlasciwa klasa """
start = IpFieldDescriptor('_start_int')
stop = IpFieldDescriptor('_stop_int')
def __init__(self, start, stop):
self.start = start
self.stop = stop
if __name__ == '__main__':
iprange = IpRange('9', '13')
# konstruktor
print iprange.start, type(iprange.start)
print iprange._start_int, type(iprange._start_int)
print iprange.stop, type(iprange.stop)
print iprange._stop_int, type(iprange._stop_int)
# ustawianie
iprange.start = '14'
iprange.stop = '20'
print iprange.start, type(iprange.start)
print iprange._start_int, type(iprange._start_int)
print iprange.stop, type(iprange.stop)
print iprange._stop_int, type(iprange._stop_int)
ps. co to są "dyskryptory" ? czy to się tak tłumaczy na nasz język ?
--
sacre
Technical Details
Message-ID:
<her5pc$22d$1@inews.gazeta.pl>Path:
mbox-mo1.pugleaf.net!news-archive.icm.edu.pl!news.gazeta.pl!not-for-mailReferences:
<slrnhh0li5.ljo.beorn@pino.cyberdeck.pl> <slrnhh0pgf.llt.beorn@pino.cyberdeck.pl>Show Full Headers
Complete Article Headers
Path: mbox-mo1.pugleaf.net!news-archive.icm.edu.pl!news.gazeta.pl!not-for-mail From: sacre <sacrebis@wp.pl> Newsgroups: pl.comp.lang.python Subject: Re: dyskryptory Date: Sat, 28 Nov 2009 13:40:53 +0100 Organization: "Portal Gazeta.pl -> http://www.gazeta.pl" Lines: 65 Message-ID: <her5pc$22d$1@inews.gazeta.pl> References: <slrnhh0li5.ljo.beorn@pino.cyberdeck.pl> <slrnhh0pgf.llt.beorn@pino.cyberdeck.pl> NNTP-Posting-Host: 82-235-158-94.jjs-isp.pl Mime-Version: 1.0 X-Trace: inews.gazeta.pl 1259412077 2125 94.158.235.82 (28 Nov 2009 12:41:17 GMT) X-Complaints-To: usenet@agora.pl NNTP-Posting-Date: Sat, 28 Nov 2009 12:41:17 +0000 (UTC) X-User: sacrebis In-Reply-To: <slrnhh0pgf.llt.beorn@pino.cyberdeck.pl> User-Agent: Thunderbird 2.0.0.23 (Windows/20090812) Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit