Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Python support something like literal objects?

In Scala I could define an abstract class and implement it with an object:

abstrac class Base {
    def doSomething(x: Int): Int
}

object MySingletonAndLiteralObject extends Base {
    override def doSomething(x: Int) = x*x
}

My concrete example in Python:

class Book(Resource):

    path = "/book/{id}"

    def get(request):
        return aBook

Inheritance wouldn't make sense here, since no two classes could have the same path. And only one instance is needed, so that the class doesn't act as a blueprint for objects. With other words: no class is needed here for a Resource (Book in my example), but a base class is needed to provide common functionality.

I'd like to have:

object Book(Resource):

    path = "/book/{id}"

    def get(request):
        return aBook

What would be the Python 3 way to do it?

like image 808
deamon Avatar asked Aug 19 '10 08:08

deamon


1 Answers

Use a decorator to convert the inherited class to an object at creation time

I believe that the concept of such an object is not a typical way of coding in Python, but if you must then the decorator class_to_object below for immediate initialisation will do the trick. Note that any parameters for object initialisation must be passed through the decorator:

def class_to_object(*args):
    def c2obj(cls):
        return cls(*args)
    return c2obj

using this decorator we get

>>> @class_to_object(42)
... class K(object):
...     def __init__(self, value):
...         self.value = value
... 
>>> K
<__main__.K object at 0x38f510>
>>> K.value
42

The end result is that you have an object K similar to your scala object, and there is no class in the namespace to initialise other objects from.

Note: To be pedantic, the class of the object K can be retrieved as K.__class__ and hence other objects may be initialised if somebody really want to. In Python there is almost always a way around things if you really want.

like image 146
Muhammad Alkarouri Avatar answered Sep 27 '22 22:09

Muhammad Alkarouri