无法理解内心阶级的结果

时间:2014-12-17 12:33:46

标签: python

我在学习Python的InnerClass时遇到了一个问题

class Innerclass:
    "the example of innerclass"
    string='hello world'

    class inner_class:
        msg='inner class'
        print(msg)

    def func0(self):
        print(self.string)
        print("public method")
        self._func1()  #the use of private method

    def _func1(self):   #private method can't be used directly
        print(self.string)
        print("private method")

    @classmethod
    def classfun2(self):
        print(self.string)
        print("class method")

    @staticmethod
    def staticfun3():
        print(Innerclass.string)
        print("static method")


g=Innerclass()
#public method and private method g.func0()
#class method g.classfun2()
#static method
g.staticfun3()

结果:

inner class
hello world
public method
hello world
private method
hello world
class method
hello world
static method

我感到困惑的是,为什么'内部阶级'首先不打印

1 个答案:

答案 0 :(得分:4)

首先,内部类非常在Python中很少有用。在另一个类中定义一个类没有特别的优势,并且通常没有太多理由这样做。

那就是说,你的问题并不是特别针对内部类:对于一个独立的类也会发生同样的问题。类定义本身是可执行语句,并且在读取类定义时执行类级别的任何操作。所以任何print语句都会在读取后立即执行。

请注意,您永远不会实例化inner_class,因此不清楚为什么您希望它最后打印,无论如何。