class object's attribute is also the instance's attribute?
Ulrich Eckhardt
ulrich.eckhardt at dominolaser.com
Thu Aug 30 07:22:19 EDT 2012
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
More information about the Python-list
mailing list