开发者

why my code only print 'bbb' once,and it does not run wrong unexpectedly

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


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.


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

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


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜