creating class objects inside methods

Simon Forman sajmikins at gmail.com
Sun Oct 4 05:48:00 CEST 2009


On Sat, Oct 3, 2009 at 11:32 PM, horos11 <horos11 at gmail.com> wrote:
> All,
>
> I've got a strange one..
>
> I'm trying to create a class object inside another class object by
> using the code template below (note.. this isn't the exact code.. I'm
> having difficulty reproducing it without posting the whole thing)
>
> Anyways, the upshot is that the first time the Myclass() constructor
> is called, the __init__ function gets executed.. The second time, it
> calls the '__call__' method (and dies, because I don't have a call
> method defined).
>
> To get around this, I've made __call__ a synonym of __init__, which is
> a horrid hack, and doesn't help me much (since I don't have a good
> idea what's going on).
>
> So - anyone have an idea of what's going on here? It looks like the
> second time, the Myclass() call is interpreted as a class instance,
> not a  class object, but that seems odd to me.. Is this a python bug?
> I'm seeing it in 2.6..If necessary, I can post the whole piece of
> code..
>
> Ed
>
> class Myclass:
>
>    def __init__(self, b='default1', c='default2'):
>
>        self.b = b;
>        self.c = c;
>
>    def function(self):
>
>         other = Myclass();
>         return(other)
>
> a = Myclass();
>
> b = a.function()
> --
> http://mail.python.org/mailman/listinfo/python-list
>


class Myclass:
    def __init__(self, b='default1', c='default2'):
        self.b = b
        self.c = c

    def function(self):
        other = Myclass()
        return other

a = Myclass()
b = a.function()


>>> a
<__main__.Myclass instance at 0x95cd3ec>
>>> b
<__main__.Myclass instance at 0x95cd5ac>


What's the problem?


(Also, you can leave out the ';' at the end of statements. And
'return' isn't a function, you can leave out the ()'s.



More information about the Python-list mailing list