tags:

views:

108

answers:

3
class a:
    class __b__(object):
        print 'bbb'

b=a()
b.__b__()
b.__b__()
b.__b__()
a.__b__()
a.__b__()
a.__b__()

it print 'bbb' only once, thanks

+3  A: 

You don't explain what you are trying to do, but I think what you mean is:

class a:
    def __b__(object):
        print 'bbb'
Charles E. Grant
Why the down votes? This may very well be what the question is asking, how often do you even use subclasses in python?
Jeffrey Aylesworth
+4  A: 

When python creates a class, it does so by executing the code within the class definition exactly once, therefore creating the class namespace, etc...

If you wanted it to run each time you called it, you need to put your code in the __init__ method (which is the constructor).

class a:
    class b:
        def __init__(self):
            print 'bbb'

a.b()
a.b()

That will print bbb 2x. Notice that you don't need an instance of a() to access a.b because class b is simply an attribute of class a. Your really don't gain much by nesting classes in python.

Notice I did not use __b__, because python reserves words that start and end with double underscores.

gahooa
Just a note; if you're using python 2.x, print is not a function, so adding the parentheses may give you weird results.
Jeffrey Aylesworth
+2  A: 

The class __b__ statement executes exactly once (when the class a statement executes) and that's the only case in which you're printint anything. The various instantiations are totally irrelevant (none of them has anything to do with the printing).

Alex Martelli