请问各位大侠,类中的方法在内存中的存储是在类中还是对象中?
In [263]: class Sample(object):
...: def ordinary(self):
...: print "I'm a ordinary method"
...: @classmethod
...: def clsmethod(cls):
...: print "I'm a class method"
...: @staticmethod
...: def stcmethod():
...: print "I'm a static method"
...:
In [264]: a = Sample()
In [265]: b = Sample()
In [266]: a.ordinary == Sample.ordinary # 普通方法,各自存储
Out[266]: False
In [267]: a.ordinary == b.ordinary
Out[267]: False
In [268]: a.clsmethod == Sample.clsmethod # 类方法存储在类中
Out[268]: True
In [269]: a.stcmethod == Sample.stcmethod # 静态方法存储在类中
Out[269]: True
In [270]: a.ordinary.im\_func == Sample.ordinary.im\_func
Out[270]: True
其实既不是存储在类中也不是存储在对象中。应该说在类的元数据(描述一个类的信息,或者叫metadata)中,存储了方法的指针。当然这个是对于python解释器内部来说的。
而类的静态成员和对象的实例成员,则是单独存储的。
这个要区分classmethod staticmethod和普通方法的。
方法不是存储在类或者对象中,它在内存中归属于类。
在系统内设定的类里面