[Baypiggies] Trivial OOP pattern problem
Shannon -jj Behrens
jjinux at gmail.com
Sat Jun 16 02:56:26 CEST 2012
(Slightly off topic.)
I am a language guy, so I love looking at other languages for cool
features. You're looking for a way to chain a bunch of method calls
together, a la jQuery. It turns out that Dart recently added a feature
called method cascades that solve this problem:
myTokenTable
..add("aToken");
..add("anotherToken");
..add("theUmpteenthToken");
..setTitle("foo");
..setBackgroundColor("green");
http://news.dartlang.org/2012/02/method-cascades-in-dart-posted-by-gilad.html
I'm not encouraging you to switch to Dart; I just think it's interesting.
-jj
On Thu, Jun 14, 2012 at 9:53 PM, Ian Zimmerman <itz at buug.org> wrote:
>
> I am writing some code using the cairo drawing library, or rather the
> pycairo binding to it. Unfortunately I sense a bit of API misdesign
> with the binding. To draw into a context ctx which I obtained somewhat
> like this:
>
> import cairo as C
>
> ctx = C.Context(surface)
>
> I am supposed to write a series of calls like this:
>
> ctx.set_source_rgb(1.0, 1.0, 1.0)
> ctx.rectangle(0.0, 0.0, float(rw), float(rh))
> ctx.fill()
> ctx.scale(sx, sy)
>
> ... and it piles up. Each of these methods returns None, whilst it
> should conceivably return self, adding a lot of convenience:
>
> ctx.set_source_rgb(1.0, 1.0, 1.0).rectangle(0.0, 0.0, float(rw),
> float(rh)).fill()
>
> I would like to write a wrapper class around Context to enable this
> usage, but I don't know how to do that sanely. Sure, I could do this:
>
> class ContextWrapper(object):
>
> def __init__(self, surface):
> self.ctx = C.Context(surface)
>
> def fill(self):
> self.ctx.fill()
> return self
>
> def scale(self, sx, sy):
> self.ctx.scale(sx, sy)
> return self
>
> ...
>
> but then I have to wrap each method explicitly, or at least each method
> I use. I don't consider that sane.
>
> Is there a trick I am missing, perhaps using __dict__ or __getattr__ by
> which I could wrap all the methods wholesale?
>
> --
> Ian Zimmerman
> gpg public key: 1024D/C6FF61AD
> fingerprint: 66DC D68F 5C1B 4D71 2EE5 BD03 8A00 786C C6FF 61AD
> http://www.gravatar.com/avatar/c66875cda51109f76c6312f4d4743d1e.png
> Rule 420: All persons more than eight miles high to leave the court.
> _______________________________________________
> Baypiggies mailing list
> Baypiggies at python.org
> To change your subscription options or unsubscribe:
> http://mail.python.org/mailman/listinfo/baypiggies
>
--
In this life we cannot do great things. We can only do small things with
great love. -- Mother Teresa
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/baypiggies/attachments/20120615/d69bff2c/attachment-0001.html>
More information about the Baypiggies
mailing list