Bobbing for Kernels

See Bob. See Bob bob. Bob, Bob, bob!

bimorphic properties, too.

Posted by kernelbob on June 26, 2008

I coined the term, bimorphic method, last week.  Shortly after I wrote about them, I found I wanted a bimorphic property too.  It’s the same idea: create a decorator that turns a method into a property getter for both the class object and instances of the class.  Here’s an example.

>>> class MyClass:
...     @bimorphicproperty
...     def my_property(cls, self):
...         if self:
...             return 'instance property'
...         return 'class property'
...
>>> my_obj = MyClass()
>>> my_obj.my_property
'instance property'
>>> MyClass.my_property
'class property'

And here’s the implementation.  I only implemented the getter — the other two methods are left as an exercise for the reader.

class property(object):

    def __init__(self, fget=None, fset=None, fdel=None, doc=None):
        self.fget = fget
        self.fset = fset
        self.fdel = fdel
        self.__doc__ = doc

    def __get__(self, obj, type=None):
        return self.fget(type, obj)

I was reading What’s New in Python 2.6 last night.  In 2.6, the property mechanism has been extended so you can use a decorator to declare the setter and deleter methods as well as the getter.  It’s a good idea and another example of how the Python implementers grow the language tastefully.  That extension would be useful for bimorphicproperty, too.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: