Server!/Horror! I have a magnet and I don't mind using it!

Python Class Methods

Just a short reminder how to easily create class methods in python. Useful for creating factory methods that return the instance of a certain class.

user@localhost:~$ python
Python 2.4.4 (#2, Apr 15 2008, 23:43:20)
[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information.</p>
<p>>>> class foo(object):
...     def __init__(self, s):
...             self.s = s
...     @classmethod
...     def from_string(cls, in_):
...             return cls(in_)
...     @classmethod
...     def from_int(cls, in_):
...             return cls(int(in_))
...
>>> s = foo.from_string(&quot;foo&quot;)
>>> s = foo.from_int(&quot;foo&quot;)
Traceback (most recent call last):
File &quot;&quot;, line 1, in ?
File &quot;&quot;, line 9, in from_int
ValueError: invalid literal for int(): foo
>>> s = foo.from_int(&quot;2&quot;)
>>> s = foo.from_int(&quot;0x2&quot;)
Traceback (most recent call last):
File &quot;&quot;, line 1, in ?
File &quot;&quot;, line 9, in from_int
ValueError: invalid literal for int(): 0x2
>>> s = foo.from_int(0xe)
>>> s.s
14

This in fact works quite fine except for one thing:

Python method are first class objects, if you have die above in a module named foo.py you will need the following code:

Python 2.6.4 (r264:77598, Jan 18 2010, 11:44:15)
[GCC 4.3.4] on linux2
>>> import foo
>>> o = foo.foo.from_string(&quot;1&quot;)
>>> o.s
'1'

Quite a lot of typing, you may want to consider the following:

Python 2.6.4 (r264:77598, Jan 18 2010, 11:44:15)
[GCC 4.3.4] on linux2
Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information.
>>> import foo
>>> foo.from_string(&quot;a&quot;)
<foo.foo object at 0x7f0c78d94350>
>>> o = foo.from_string(&quot;a&quot;)
>>> o.s
'a'

A lot less to type isn't it?

To get that working just create a module that looks like this:

def from_string(value):
    return foo(value)</p>
<p>def from_int(value):
    return foo(int(value))</p>
<p>class foo(object):
    def __init__(self, s):
            self.s = s

Generated: 2017-11-02 10:20:47 +0100