How to make a method into a property without using the @property decorator

Discussion in 'Python' started by Phlip, Oct 23, 2010.

  1. Phlip

    Phlip Guest

    Pythonistas:

    Here's the property decorator:

    @property
    def foo(self): return 'bar'

    If I generate foo dynamically, how to I make it a property?

    setattr(self, 'foo', property(lambda: 'bar'))

    Variations of that are apparently not working.

    (I'm heading for a proxy pattern, where if you never call the
    generated prop, you never hit the database to load it into memory.)

    --
    Phlip
    http://zeekland.zeroplayer.com/
     
    Phlip, Oct 23, 2010
    #1
    1. Advertising

  2. Phlip

    Peter Otten Guest

    Phlip wrote:

    > Pythonistas:
    >
    > Here's the property decorator:
    >
    > @property
    > def foo(self): return 'bar'
    >
    > If I generate foo dynamically, how to I make it a property?
    >
    > setattr(self, 'foo', property(lambda: 'bar'))
    >
    > Variations of that are apparently not working.


    You have to put the property descriptor into the class, not an instance:

    >>> class A(object):

    .... pass
    ....
    >>> a = A()
    >>> setattr(type(a), "foo", property(lambda self: "FOO"))
    >>> a.foo

    'FOO'
    >>> A().foo

    'FOO'

    > (I'm heading for a proxy pattern, where if you never call the
    > generated prop, you never hit the database to load it into memory.)


    You may be better off with __getattr__().

    Peter
     
    Peter Otten, Oct 23, 2010
    #2
    1. Advertising

  3. Phlip

    Phlip Guest

    On Oct 23, 8:01 am, Peter Otten <> wrote:

    > You may be better off with __getattr__().


    Ayup, thanks. (Maybe I should have googled for "python equivalent of
    ruby method_missing", hmm?;)
     
    Phlip, Oct 23, 2010
    #3
    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. jtl.zheng
    Replies:
    5
    Views:
    401
    jtl.zheng
    Jul 25, 2006
  2. Méta-MCI
    Replies:
    5
    Views:
    253
    Duncan Booth
    Feb 6, 2007
  3. glomde
    Replies:
    5
    Views:
    547
    glomde
    Mar 29, 2007
  4. Zaza
    Replies:
    0
    Views:
    656
  5. Replies:
    10
    Views:
    149
Loading...

Share This Page