Attribute definition, WHY?
bhellao at my-deja.com
bhellao at my-deja.com
Tue Sep 12 15:09:15 EDT 2000
One of the ways they are different is in inheritance.
For example:
# the original script
class A:
color = "Blue"
def __init__(self):
pass
class B:
def __init__(self):
self.color = 'Blue'
>>> a = A(); b = A()
>>> a.color; b.color
'Blue'
'Blue'
>>> a.color = 'Red'
>>> b.color
'Blue' <-- did not change the 'color' value of instance 'b'
>>> a = B(); b = B()
>>> a.color; b.color'Blue'
'Blue'
'Blue'
>>> a.color = 'Red'
>>> b.color
'Blue' <-- did not change the 'color' value of instance 'b'
However,
class D(A): # subclassing A
def __init__(self):
pass
class B:
def __init__(self):
self.color = 'Blue'
class E(B): # subclassing B
def __init__(self):
pass
>>> d = D(); e = E()
>>> d.color
'Blue'
>>> e.color # the init method of class B was not automatically called,
# so the 'color' never became an instance variable.
AttributeError: 'E' instance has no attribute 'color'
Of course you could invoke the init method by
class E(B): # subclassing B
def __init__(self):
B.__init__(self)
which would give the result
>>> e.color
'Blue'
Hope this helps.
In article <slrn8rssnb.on.matt at happy-hour.mondoinfo.com>,
matt at mondoinfo.com (Matthew Dixon Cowles) wrote:
> On Tue, 12 Sep 2000 17:17:42 GMT, bragib at my-deja.com
> <bragib at my-deja.com> wrote:
>
> >Why would you want to do the following:
> >
> >class A:
> > attr1 = [1,2]
> > def __init__(self,name):
> > self.name = name
> >
> >and not
> >
> >class A:
> > def __init__(self,name):
> > self.name = name
> > self.attr1 = [1,2]
> >
> >Are there benefits to the first definition?
>
> Bragi,
> In the first definition, the value of attr1 is shared by the whole
> class. That's useful for counters and whatnot. So, given the first
> definition, code like this:
>
> foo=A('foo')
> bar=A('bar')
> A.attr1=[3,4]
> print foo.attr1
> print bar.attr1
>
> would produce
>
> [3, 4]
> [3, 4]
>
> Regards,
> Matt
>
Sent via Deja.com http://www.deja.com/
Before you buy.
More information about the Python-list
mailing list