Magic?

Discussion in 'Python' started by mk, Jul 13, 2008.

  1. mk

    mk Guest

    So I was playing around with properties and wrote this:

    class lstr(str):
    def __init__(self, initval):
    self._s = initval
    self._len = len(self._s)

    def fget_s(self):
    return str(self._s)

    def fset_s(self, val):
    self._s = val
    self._len = len(self._s)

    s = property(fget_s, fset_s)

    def fget_len(self):
    return self._len

    def fset_len(self, val):
    raise AttributeError, "Attribute is read-only."

    len = property(fget_len, fset_len)


    I obviously aimed at defining setters and getters for 's' and 'len'
    attributes via using properties to that.

    However, it appears that somehow this object prints the value of 's'
    attribute without me setting any specific methods to do that:

    >>> astr = lstr('abcdef')
    >>> astr

    'abcdef'
    >>> astr.swapcase()

    'ABCDEF'

    How does it know to do that? I mean, I can understand how it knows to do
    that since I used property:

    >>> astr.s

    'abcdef'

    >>> vars(astr)

    {'_len': 6, '_s': 'abcdef'}

    How does the instance know to use _s value to return when the instance
    is called?

    Is this due to some trick handling of overriden __init__ method (i.e. it
    knows to treat initval argument somehow specially)? Some other way? If
    so, how?
    mk, Jul 13, 2008
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Nilsson Mats

    Wrapper on magic line?

    Nilsson Mats, Dec 9, 2003, in forum: Perl
    Replies:
    0
    Views:
    606
    Nilsson Mats
    Dec 9, 2003
  2. Martin

    Application name magic

    Martin, Jan 28, 2004, in forum: ASP .Net
    Replies:
    2
    Views:
    307
    Martin
    Jan 28, 2004
  3. =?Utf-8?B?U2hhd24=?=

    Magic Trick Datagrid Delete Row

    =?Utf-8?B?U2hhd24=?=, Apr 6, 2005, in forum: ASP .Net
    Replies:
    3
    Views:
    3,438
    =?Utf-8?B?U2hhd24=?=
    Apr 6, 2005
  4. lawrence

    bad magic number

    lawrence, Sep 20, 2003, in forum: Java
    Replies:
    5
    Views:
    820
    Roedy Green
    Oct 10, 2003
  5. Giles Bowkett
    Replies:
    9
    Views:
    395
    Giles Bowkett
    Dec 17, 2007
Loading...

Share This Page