python语言class\object\instance区别及用法,pythoninstance,Python类的用法第一


Python类的用法

第一种方法:

class OneObjectCreater():    pass

第二种方法带有类的参数

class TwoObjectCreater(object):    pass

都使用print出来,却有细微的差别;

if __name__ == "__main__":    print OneObjectCreater()    print TwoObjectCreater()

第一种输出:

<__main__.OneObjectCreater instance at 0xb7736eac>

第二种输出:

<__main__.TwoObjectCreater object at 0xb7736eac>

这样的区别对于使用有什么讲究,什么时候使用calss(),什么时候使用class(object)?

Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.

自从python2.2开始,继承与Object的class被叫做"New-Style Class"。

供参考:

http://stackoverflow.com/questions/54...

http://docs.python.org/2/reference/da...

http://www.python.org/doc/newstyle/

class()叫做经典类,而class(object)叫做新式类,新式类貌似是从2.2开始引入的。经典类是为了向后兼容,所以最好还是使用新式类,至于两者有什么区别?我也在学习:)

编橙之家文章,

评论关闭