Python Class Best Practice
Rod Person
rodperson at verizon.net
Tue Dec 4 19:07:09 EST 2007
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
On Tue, 04 Dec 2007 15:51:18 -0800
Gary Herron <gherron at islandtraining.com> wrote:
> Rod Person wrote:
> >
> > 1:
> > class Foo(object):
> > member1=''
> > member2=0
> >
> > def __init__(self,member1='',member2=0):
> > self.member1 = member1
> > self.member2 = member2
> >
> > 2:
> > class Foo(object):
> > def __init__(self,member1='',member2=0):
> > self.member1 = member1
> > self.member2 = member2
> >
> >
> Both examples will store values for member1 and member2 in every
> instance. Any code that accesses self.member1 (or 2) will get the
> value stored in the instance.
>
> Example 1 which also creates two *class* members of the same name
> won't affect the conclusion of the previous paragraph. The two
> values in the class will be shadowed by each instances members of the
> same name.
>
> But now I need to ask, what did you expect to happen here?
Well I guess I should say that I'm coming to Python from Delphi, so I
am used to creating classes like in #1, but I'm used to having to
declare a scope for each member. Not having a scope declaration is
really throwing me some.
>
> * If you thought those two extra assignments in example 1 effected
> the execution or storage in the __init__ (or any other method), you
> were mistaken.
>
Yes, this is what I thought. I thought that declaring member1='' would
just assign the a default value on creation of the class (as in
Delphi). I probably shouldn't have give the parameters in the __init__
a default value in example 1.
> Gary Herron
Thanks.
- --
Rod
http://roddierod.homeunix.net:8080
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.7 (FreeBSD)
iD8DBQFHVeuucZAIaGStcnARAgEKAJ4/bJW9GSNTsmSgyOTokbCkEQFO7ACdErME
50Mgzge48M2z+nymifkByqo=
=e3gV
-----END PGP SIGNATURE-----
More information about the Python-list
mailing list