Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > How to make a method into a property without using the @property decorator

Reply
Thread Tools

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

 
 
Phlip
Guest
Posts: n/a
 
      10-23-2010
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/
 
Reply With Quote
 
 
 
 
Peter Otten
Guest
Posts: n/a
 
      10-23-2010
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
 
Reply With Quote
 
 
 
 
Phlip
Guest
Posts: n/a
 
      10-23-2010
On Oct 23, 8:01*am, Peter Otten <(E-Mail Removed)> wrote:

> You may be better off with __getattr__().


Ayup, thanks. (Maybe I should have googled for "python equivalent of
ruby method_missing", hmm?
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: How include a large array? Edward A. Falk C Programming 1 04-04-2013 08:07 PM
Enhanced property decorator Daniel Python 4 09-02-2008 07:26 AM
Sitemesh : set property from decorated page for decorator Zaza Java 0 07-04-2008 04:19 PM
Why doesnt __getattr__ with decorator dont call __get_method in decorator glomde Python 5 03-29-2007 02:48 PM
can I make this two method into one method? jtl.zheng Java 5 07-25-2006 02:38 AM



Advertisments