Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!news.mixmin.net!news.musoftware.de!wum.musoftware.de!fu-berlin.de!uni-berlin.de!not-for-mail From: Ulrich Eckhardt Newsgroups: comp.lang.python Subject: Re: class object's attribute is also the instance's attribute? Date: Thu, 30 Aug 2012 13:22:19 +0200 Lines: 41 Message-ID: <503F4CEB.9070408@dominolaser.com> References: <3830e549-cb6d-4bcf-af45-f7c83ad2b65e@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 8bit X-Trace: news.uni-berlin.de J8WCM9hFxzaOIyDgljCl5QsTqPKU84+c+wrDt7j499984eyzgzFQKUgAY2Wg== X-Orig-Path: satorlaser.homedns.org!not-for-mail User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:14.0) Gecko/20120713 Thunderbird/14.0 In-Reply-To: <3830e549-cb6d-4bcf-af45-f7c83ad2b65e@googlegroups.com> Xref: csiph.com comp.lang.python:28104 Am 30.08.2012 12:55, schrieb 陈伟: > class A(object): > d = 'it is a doc.' > > t = A() > > print t.__class__.d > print t.d > > the output is same. You could go even further: print id(t.__class__.d) print id(t.d) which should show you that they are not just equal but identical. > so it means class object's attribute is also the instance's > attribute.is it right? Yes. This is even useful sometimes: class Point(object): x = 0 y = 0 This will cause every Point to have two attributes x and y that have a default value 0. Note that setting this attribute on an instance does not change the class' attribute, just in that that was what confused you. However, if the attribute references a mutable type (e.g. a list) this can cause problems because the instance (see id() above) is the same and thus modifications affect both the class and all instances. Uli