A Trivial Question

Chris Rebert clp2 at rebertia.com
Thu Sep 29 00:06:14 CEST 2011


On Wed, Sep 28, 2011 at 2:53 PM, Tayfun Kayhan
<tayfun92_kayhan at yahoo.com> wrote:
> I accidentally wrote such a code (below) while trying to write sth else for
> my application but i am now just wondering much how to run the class Foo, if
> it is possible. Is not it weird that Python does not give any error when I
> run it ? Sorry for that it's pretty unimportant question according to the
> other questions being asked here :D
> def trial():
>     class Foo(object):
>         def __init__(self):
>             print("Hello, world!")
> trial() # not worked, as expected.

Right now, you've merely defined a class in the local scope of a
function, which is perfectly valid, although you don't take advantage
of this, so there's no particular reason to put the class definition
inside trial(). Foo.__init__() only gets called when you create an
instance of Foo, which you aren't doing currently, hence why "Hello,
world!" isn't printed.

Try this:

def trial():
    class Foo(object):
        def __init__(self):
            print("Hello, world!")
    Foo()
trial()


Or this:

class Foo(object):
    def __init__(self):
        print("Hello, world!")

def trial():
    Foo()
trial()


Cheers,
Chris
--
http://rebertia.com



More information about the Python-list mailing list